Serving Django Static Files on Heroku (Posted on December 15th, 2012)

One of my goals when creating this blog was to create a blog that I never had to pay for. Luckily Heroku's free tier allowed me to do just that. While my blog doesn't have many static files (CSS, JS and images) Heroku typically recommends that you host them on Amazon which isn't free. However, Heroku gives you 100mb of free space for your app so I wanted to take full advantage of that and the free bandwidth they offer.

I tested a few different webservers and found Tornado to work the best after some load testing with Blitz.io. The other ones I tested were CherryPy, FAPWS3, and Gunicorn with Tornado. After a bit of tinkering with getting Tornado to host static files here is what I came up with (go ahead and replace "burstolio" with the name of your app):

import os, sys
import django.core.handlers.wsgi
from tornado import httpserver, ioloop, wsgi, web

from optparse import OptionParser
parser = OptionParser()

parser.add_option('--port', dest='port')

options, args = parser.parse_args()
        
def runserver():
    app_dir = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(os.path.dirname(app_dir))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'burstolio.settings'
    wsgi_app = wsgi.WSGIContainer(django.core.handlers.wsgi.WSGIHandler())
    application = web.Application([
        (r"/static/(.*)", web.StaticFileHandler, {"path": "/app/burstolio/static"}),
        (r".*", web.FallbackHandler, dict(fallback=wsgi_app)),
    ])

    server = httpserver.HTTPServer(application)
    server.listen(options.port)
    try:
        ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == '__main__':
    runserver()

The first part allows me to specify a port which Heroku will assign automatically. Getting into the runserver function we first start by adding the app to the system path so that our app can be found. After that we create a WSGI (Web Server Gateway Interface) container to hold our app in a way that we can serve to users.

The next part is the important part where the web app's URLs are setup. It's important that the static files go first otherwise Tornado will match the WSGI container regex which will 404. Make sure that your settings.py file has the STATIC_URL and STATIC_ROOT set to match the regex you specify for the StaticFileHandler. Here is an example of how I setup my settings.py. Once the web app is setup the rest is as simple as creating an HTTP server and listening on the specified port.

If you're running on Heroku and want to give this a try your procfile should look something like:

web: python tornadows.py --port=$PORT

If you know of a better way to host static files on heroku, run into any problems or have any questions let me know in the comments!

Tags: Django, Heroku

Comments:

  • Shannon -jj Behrens - 1 year, 11 months ago

    Instead of setting up StaticFileHandler explicitly, I think you can do:

    application = web.Application( static_path=settings.STATIC_ROOT, handlers=[ (r".*", web.FallbackHandler, dict(fallback=wsgi_app)), ])

    reply

  • Max Burstein - 1 year, 11 months ago

    I think you are correct. Not sure if that method was around back when I first worked on this blog. I did come across it while launching my new site http://problemotd.com and it worked exactly the same. Always good to have options :)

    reply

  • Salesforce Training in Chennai - 7 months, 1 week ago

    Rename your index.html to home.html or something similar. Create an index.php file with the following code:

    <?php include_once("home.html"); ?>

    That’s it!

    reply

  • easiest way to hack top eleven - 7 months ago

    Get the easiest way here to hack top eleven without paying any money.

    reply

  • bonton - 6 months, 3 weeks ago

    My buddy votes I can <a href="http://essaywritingservicez.com/write-my-essay-for-me/">will you write my essay for me</a> from this locale. How do I go about this being sum I can discover here is info on what to squint for in a composition or a author? Do you get a table of utilitys I can decide from?

    reply

  • Anonymous - 6 months, 3 weeks ago

    [url=http://plus.google.com/+Sunshinesoftwash/videos]commercial roof cleaning Orlando[/url]

    reply

  • Puja Kumari - 5 months, 3 weeks ago

    Thanks for post this helpful post - Please visit for More information about: http://www.top9th.in/packers-and-movers-pune/ http://www.top9th.in/packers-and-movers-noida/ http://www.top9th.in/packers-and-movers-chennai/ http://www.top9th.in/packers-and-movers-kolkata/ http://www.top9th.in/packers-and-movers-ahmedabad/ http://www.top9th.in/packers-and-movers-surat/

    reply

  • Puja Kumari - 5 months, 3 weeks ago

    Thanks for Nice and Informative Post. This article is really contains lot more information about This Topic http://www.top9th.in/packers-and-movers-bangalore/ http://www.top9th.in/packers-and-movers-hyderabad/ http://www.top9th.in/packers-and-movers-mumbai/ http://www.top9th.in/packers-and-movers-delhi/ http://www.top9th.in/packers-and-movers-gurgaon/ http://www.top9th.in/

    reply

  • PeakEssay.com - 4 months, 3 weeks ago

    When a Django function is organize to Heroku, assemble static is work automatically when it is configured accurately.

    reply

  • Micro Economics Assignment help - 4 months, 3 weeks ago

    Yes indeed it is a good and like it a lot love to see the things which are doing great here.

    reply

  • Hack FACBOOK - 4 months, 3 weeks ago

    Here you can see for useful webpage for free hack facebook online and ask more details to get back your facebook hacked.

    reply

  • Have a Look - 4 months, 3 weeks ago

    I have some knowledge about development, but your topic it’s too difficult and I do not understand on your topic anyways I read your different post on your blog.

    reply

  • write my paper for cheap - 4 months, 2 weeks ago

    At the point when a Django application is conveyed to Heroku, collectstatic is run naturally when it is designed legitimately.

    reply

  • marvel future fight hack - 4 months, 1 week ago

    This specific post is certainly created having conventional text as well as ornamented with brilliant snap shots. The article author seems to have an extremely comprehensive knowledge about this subject. That is certainly quite difficult to get a important post such as this. This articles author equipped quite diligently along with reflectively.

    reply

  • Packers Movers - 4 months ago

    Thanks for post this helpful post - Please visit for More information about:

    http://www.expert9th.in/packers-and-movers-delhi/ http://www.expert9th.in/packers-and-movers-noida/ http://www.expert9th.in/packers-and-movers-gurgaon/ http://www.expert9th.in/packers-and-movers-kolkata/ http://www.expert9th.in/packers-and-movers-ghaziabad/ http://www.expert9th.in/packers-and-movers-amritsar/


    Thanks for post this helpful post - Please visit for More information about:

    http://www.expert9th.in/packers-and-movers-bangalore/ http://www.expert9th.in/packers-and-movers-hyderabad/ http://www.expert9th.in/packers-and-movers-chennai/ http://www.expert9th.in/packers-and-movers-pune/ http://www.expert9th.in/packers-and-movers-faridabad/ http://www.expert9th.in/packers-and-movers-kochi/


    Thanks for post this helpful post - Please visit for More information about:

    http://www.expert9th.in/packers-and-movers-mumbai/ http://www.expert9th.in/packers-and-movers-surat/ http://www.expert9th.in/packers-and-movers-navimumbai/ http://www.expert9th.in/packers-and-movers-ahmedabad/ http://www.expert9th.in/packers-and-movers-chandigarh/ http://www.expert9th.in/packers-and-movers-jamshedpur/

    reply

  • Packers Movers - 4 months ago

    Thanks for Nice and Informative Post. This article is really contains lot more information about This Topic http://www.top9th.in/packers-and-movers-bangalore/ http://www.top9th.in/packers-and-movers-hyderabad/ http://www.top9th.in/packers-and-movers-mumbai/ http://www.top9th.in/packers-and-movers-delhi/ http://www.top9th.in/packers-and-movers-gurgaon/ http://www.top9th.in/


    Thanks for post this helpful post - Please visit for More information about: http://www.top9th.in/packers-and-movers-pune/ http://www.top9th.in/packers-and-movers-noida/ http://www.top9th.in/packers-and-movers-chennai/ http://www.top9th.in/packers-and-movers-kolkata/ http://www.top9th.in/packers-and-movers-ahmedabad/ http://www.top9th.in/packers-and-movers-surat/

    reply

  • essay writing companies - 3 months, 4 weeks ago

    yes you are right, i agree with your point.

    reply

  • new year 2016 - 3 months, 4 weeks ago

    It is a great article. You will surely like this also because it is a great stufff http://www.happynewyear2016-images.com http://www.recipefrance.com/2015/04/meilleur-images-de-bonne-annee-2016.html http://www.felizanonuevo2016frases.com

    reply

  • help with assignment - 3 months, 3 weeks ago

    I enjoy a couple of from the Information which has been written, and particularly the comments posted I will definitely be visiting again.

    reply

  • labor day mattress sale 2015 - 1 month, 3 weeks ago

    Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing...

    reply

  • Assignment Writing Service UK - 1 month, 3 weeks ago

    Tornado will match the WSGI container regex which will 404.

    reply

  • Neymar Brazil - 1 month, 3 weeks ago

    Being ranked third of the best among 100 4-4-2 football players, the youngster has come to being one of the top Barcelona players despite all the criticism he has received over the past years.

    reply

  • adjustable bed frame - 1 month, 3 weeks ago

    I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

    reply

  • is it bad to sleep on your stomach - 1 month, 3 weeks ago

    You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site.

    reply

  • Cara Mengatasi Rasa Nyeri Pada Payudara - 1 month, 2 weeks ago

    Great pieces. Keep posting such kind of info on your blog. I'm really impressed by your blog. Hello there, You’ve performed a great job. I’ll certainly digg it and in my opinion suggest to my friends. I am sure they’ll be benefited from this website.

    reply

  • Newamericanjackets han solo star wars awakens jack - 1 month, 2 weeks ago

    Extraordinary subject! This article is satisfied to seek out with useful details and very constructive.

    reply

  • Map Sewa Mobil Surabaya Indonsia Car Rental Hire - 1 month, 1 week ago

    HAPPY NEW YEAR 2016 HAPPY NEW YEAR 2016 HAPPY NEW YEAR 2016 HAPPY NEW YEAR 2016

    reply

  • Cara untuk Menyembuhkan Gagal Ginjal - 1 month, 1 week ago

    The article you write is very nice, a lot of interesting things that I got after reading the information you have to say this. Thank you very much for sharing this impressive.

    reply

  • hacked fb - 1 month ago

    100% free <a href="http://facebook-hack7.blogspot.com/">how to hack facebook</a> turested site and enjoy any usear so click here

    reply

  • how to make money online - 1 month ago

    100% free <a href="http://facebook-hack7.blogspot.com/">how to hack facebook</a> turested site and enjoy any usear so click here

    reply

  • Hamariweb7 - 1 month ago

    top sites <a href="http://hamariweb7.blogspot.com/" target="_blank">Games,softwares & etc</a> free 100% turesting site so click here

    reply

  • Chevrolet Dealership Brownsville - 1 month ago

    one can be sure that one experience with Chevrolet dealership Brownsville can actually make the customers love this dealership, and walk in for more offers.

    reply

  • family photography gift certificate - 1 month ago

    From here the idea of gifting family photography gift certificate certificate originates. It is best that in spite of certain gifts which have a very short lived value, a person should be gifted something memorable.

    reply

  • bmw x5 wheels - 1 month ago

    Hey – great blog, just looking around some blogs, seems a really nice platform you are using. I’m currently using WordPress for a few of my blogs but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

    reply

  • Corporate headshots sydney - 1 month ago

    It is hence required that a person makes sure that this whole process be handled in a professional manner. This is where we find the entry of Corporate headshots sydney!

    reply

  • Shaw Mail - 1 month ago

    Very good information, keep sharing this type of posts.....

    reply

  • Assignment help - 1 month ago

    I appreciate your efforts in preparing this post. I really like your blog articles.

    reply

  • Homework Help - 1 month ago

    Your blog provided us with valuable information to work with. Each & every tip of your post is awesome.

    reply

  • email marketing companies uk - 4 weeks, 1 day ago

    Email Marketing Companies UK take such responsibilities on behalf of you so that you can reach thousands of your customers in a second.

    reply

  • cheapest bulk email service - 4 weeks, 1 day ago

    Cheapest Bulk Email Service must not result cheaply as you know that there is no alternative of email marketing today to get your task executed.

    reply

  • white label email marketing - 4 weeks, 1 day ago

    You can be able to earn annual revenues through the program of our white label email marketing.

    reply

  • bulk email service uk - 4 weeks ago

    For your bulk emailing requirements the bulk email service UK is able to send out thousands of emails at a time to right destinations.

    reply

  • PPC Lagos Nigeria - 3 weeks, 6 days ago

    You can part your advertisements by making numerous renditions of the commercial's content for each of your PPC promotion bunches. That way, you can figure out which particular wording prompts the most navigate and on location changes.

    reply

  • email marketing agency uk - 3 weeks, 6 days ago

    In order to persistently get engaged with customers and build subsequent relationship with them you can make use of services offered by Email Marketing Agency UK.

    reply

  • email marketing providers uk - 3 weeks, 6 days ago

    Email Marketing Providers UK can bring the perfect solution when you are seemingly stuck on reverse.

    reply

  • add event - 3 weeks, 5 days ago

    To make an add event icon and provide detailed notification is not quite enough to make the whole programme a success. Hence, certain other factors need to be kept in mind.

    reply

  • tradeshow - 3 weeks, 4 days ago

    Tradeshow are sites of socialisation and familiarisation with other cultures.

    reply

  • business conferences - 3 weeks, 4 days ago

    Such business conferences could just make the whole arena different. By means of this, products, market scenario and future market prospects can be determined.

    reply

  • networking events - 3 weeks, 4 days ago

    It is important to remember that at all networking events, everyone is trying to do exactly what you are, you must also keep in mind that your time and energy is valuable and work accordingly.

    reply

  • trade show calendar - 3 weeks, 4 days ago

    There are a number of trade show calendars for all the different shows that come up, browsing and educating yourself about them is an absolute necessity.

    reply

  • upcoming conferences - 3 weeks, 4 days ago

    Going through trade show directories and business calendars is the first step to venturing out and attending an upcoming conference that could take your business to new heights.

    reply

  • Facial Bed - 2 weeks, 5 days ago

    Are you the woman that gets burnt instead of getting healthy? You could now look naturally beautiful if you just buy Spray tanning machine.

    reply

  • custom essay online - 1 week, 6 days ago

    Heroku typically recommends that you host them on Amazon which isn't free. We care your time and education, We have a reputation of always meeting our deadlines.

    reply

  • devendra - 1 day, 6 hours ago

    Thanks For Sharing This Post

    reply

  • Convert Webpage to PDF - 1 week, 6 days ago

    What is more interesting, after you convert webpage to PDF, if the webpage contains any photograph, the PDF file retains it with original quality.

    reply

  • Nile cruise - 1 week, 5 days ago

    The Go Nile cruise is a travel agency is a professional tour operator that offers specialized travel services to visitors in this part, having been in operation for over twenty two years.

    reply

  • happy valentines day images for facebook - 1 week, 5 days ago

    Best valentines day 2016 images, pictures, wallpapers photos, quotes, messages, sms, greetings for whatsapp, facebook sharing

    reply

  • valentines day 2016 wishes - 1 week, 5 days ago

    Best valentines day 2016 images, pictures, wallpapers photos, quotes, messages, sms, greetings for whatsapp, facebook sharing

    reply

  • rose images for valentines day - 1 week, 4 days ago

    Happy Rose Day Images for valentines day 2016 lovely quotes, romantic wishes, pictures and HD Wallpaper in 3D also (animated gif) for boyfriend, girlfriend, wife, husband

    reply

  • Mixed Martial Arts - 1 week ago

    Unified Rules of mixed Martial Arts clearly depicts strict guidelines for gears. As an example, fight shorts are ultra durable, and features about 2 percent stretch polyester fabrics in its construction.

    reply

  • Article Spinning Service - 6 days, 6 hours ago

    Fantastic post I like it. Keep it up

    reply

  • College Term Papers Writing Services - 6 days, 5 hours ago

    It is really difficult to find such a fantastic content with some useful information

    reply

  • Accounting Assignments Help - 6 days, 5 hours ago

    This is really great information found here, I really like your blog. Thanks very much for the share. Keep posting

    reply

  • Accounting Homework Help - 6 days, 4 hours ago

    That was an really awesome post and i like that.

    reply

  • Writing Illustration Essay Assignment Help - 6 days, 4 hours ago

    Writing Illustration Essay Assignment and Online Homework Help Writing Illustration Essay If you desire to begin an efficient illustration essay for your school or college.

    reply

  • fake tattoos - 4 days, 4 hours ago

    The temporary fake tattoos of today are no longer just for children, as most last a long time - making them ideal for adults

    reply

  • devendra - 1 day, 7 hours ago

    https://bestbulksmsproviderindia.wordpress.com/2016/02/08/how-transactional-sms-and-hlr-lookup-can-enhance-marketing-advertising-and-campaigns/

    reply