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 - 2 years, 2 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 - 2 years, 1 month 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 - 10 months 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 - 9 months, 4 weeks ago

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

    reply

  • bonton - 9 months, 2 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 - 9 months, 2 weeks ago

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

    reply

  • Puja Kumari - 8 months, 2 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 - 8 months, 2 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 - 7 months, 2 weeks ago

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

    reply

  • Ha Phuong - 3 weeks, 3 days ago

    I really thank the author of this article, the article has great significance for me, it just leads me to do better things for this life. Very meaningful, thank you very much, wish you happy.Viral Loop Review best ultimate viral wordpress them ViralLoop Review tool Viral Loop Free - Viral Loop Bonus

    reply

  • pics - 3 weeks, 1 day ago

    Free India Actress Wallpapers <a href="http://actresswallpapersin.blogspot.com/2016/04/priyanka-chopra-photo-gallery-latest.html">priyanka chopra photo gallery</a> very cute and beautyfull wallpapers.

    reply

  • namecheap coupons - 1 week, 1 day ago

    i like your blog http://www.webtechcoupons.com/offers/namecheap/

    reply

  • Margaret M Brooks - 5 days, 7 hours ago

    The post which we creating should be have some thoughts and relevance. Here it comes true and I am happy to here to read this post. Visit @ http://buyessays.us

    reply

  • <a href="https://playview.org">playview</a> - 1 day, 7 hours ago

    Thanks for sharing such great info

    reply

  • Jason - 1 day, 6 hours ago

    Thanks for sharing such great post, playview app is great <a href="https://playview.org">playview download</a>

    reply

  • Mary - 1 day, 6 hours ago

    hi, i was searching something and found playview app. Amazing for video downloading Download playview app now

    reply

  • ranaali - 23 hours ago

    Definitely imagine that which you said. Your favourite reason appeared to be on the net the simplest factor to remember of

    http://procracksoftwares.com/quick-heal-total-security-2016-key-free/

    reply

  • ranaali - 23 hours ago

    Definitely imagine that which you said. Your favourite reason appeared to be on the net the simplest factor to remember of[url=http://windowsactivatorloader.com/windows-xp-genuine-activator-loader-daz-crack/]Windows XP Genuine Activator[/url]

    <a href="http://procracksoftwares.com/iobit-driver-booster-3-pro/"> IObit Driver Booster 3 PRO</a>

    reply

  • mothers day wishes with images - 8 hours ago

    We have collected some of the best Mothers day images, Mothers day messages, Mothers day quotes, SMS, Wallpapers for sharing on whatsapp, facebook, twitter and other social media. Mothers day whatsapp images, quotes, messages, sms, greetings, wishes for facebook status, twitter sharing

    http://www.worldaroundu.com/2015/03/happy-mothers-day-whatsapp-images-messages-quotes-sms-wallpapers-facebook-status-twitter-sharing.html http://www.mothersdaymessagess.org/ http://www.mothersdayimages.org/

    reply