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, 6 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, 6 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 - 1 year, 2 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 - 1 year, 2 months ago

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

    reply

  • bonton - 1 year, 2 months 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 - 1 year, 2 months ago

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

    reply

  • Puja Kumari - 1 year, 1 month 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 - 1 year, 1 month 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 - 1 year ago

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

    reply

  • Ha Phuong - 5 months, 2 weeks 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 - 5 months, 2 weeks 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 - 5 months ago

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

    reply

  • Margaret M Brooks - 4 months, 4 weeks 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> - 4 months, 3 weeks ago

    Thanks for sharing such great info

    reply

  • Jason - 4 months, 3 weeks ago

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

    reply

  • Mary - 4 months, 3 weeks ago

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

    reply

  • ranaali - 4 months, 3 weeks 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 - 4 months, 3 weeks 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 - 4 months, 3 weeks 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

  • qeasd7r6qieygausd - 4 months, 2 weeks ago

    I like it http://www.friv2games.org.uk/ Armor http://www.y8y8co.com/ Glory http://www.85play-games.com/ Game of Thrones

    reply

  • Anonymous - 4 months, 1 week ago

    http://bollywoodbindasss.blogspot.in/2016/05/sarabjit-box-office-collections.html

    reply

  • Box Office Collection - 4 months, 1 week ago

    Thanks For Sharing This Post.

    <a href="http://bollywoodbindass.tumblr.com/post/144339300153/sarabjit-box-office-collcetion">Box Office Collections</a>

    <a href="http://bollywoodbindass1.weebly.com/blog/sarabjit-box-office-collection">Box Office Collection</a>

    reply

  • Harry - 4 months 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.webinar jeo Complete Webinar Software webinar jeo review best webinar software webinar jeo reviews - webinar jeo review and bonus - Home Pagewebinar jeo bonus - webinar jeo free - webinar jeo dowload- webinar jeo review- webinar jeo review- webinar jeo review- webinar jeo review- webinar jeo review- webinar jeo review

    Complete Webinar Software

    reply

  • voot - 3 months, 4 weeks ago

    check <a href="https://vootapp.org/">voot </a> here

    reply

  • voot - 3 months, 4 weeks ago

    check https://vootapp.org/ here

    reply

  • 9tayeri - 3 months, 3 weeks ago

    Maybe I can use that static if I want to make some program or manage my program, right? <a href="http://goo.gl/SK9Qfu">PT Trayindo Teknik Mandiri</a>

    reply

  • 9trayeri - 3 months, 3 weeks ago

    Maybe I can use that static if I want to make some program or manage my program, right? [URL=http://goo.gl/SK9Qfu]PT Trayindo Teknik Mandiri[/URL]

    reply

  • 9trayeri - 3 months, 3 weeks ago

    Maybe I can use that static if I want to make some program or manage my program, right? <a href="http://goo.gl/SK9Qfu/">PT Trayindo Teknik Mandiri</a>

    reply

  • goodboy - 3 months, 3 weeks ago

    <a href="https://playview.org">Download playview app</a>

    reply

  • Madden Deleon - 3 months, 3 weeks ago

    The article is very helpful, thank you very much . <a href="http://www.thefutoncovercompany.com/">futons</a>

    reply

  • Madden Deleon - 3 months, 3 weeks ago

    The Futon Cover Company is here to meet all your needs. With a vast collection of futon covers, this company has now become one of South Florida's biggest Futon stores. http://www.thefutoncovercompany.com/

    reply

  • Shivani Mihani - 3 months, 2 weeks ago

    Hello, Thanks For Sharing This <a href="http://whatsappquotesstatus.net/Good Morning-status-for-whatsapp-wishes/">Good Morning Status for whatsapp</a>, i love to share This Status With My Friend And family. keep updating such post.

    reply

  • Anonymous - 3 months, 2 weeks ago

    Confused among essay service vendors. Visit us for essay service reviews. http://www.essay-services-review.com/

    reply

  • Anonymous - 3 months, 2 weeks ago

    Get the best clash of clans war base that will defend your base against <a href="https://www.th8warbase.com/">th8 base</a> gowipe, gohog, gowiva

    reply

  • Source - 3 months ago

    It's just the way I like it. Get over it No need to post my site especially here. <a href="http://www.tedwed.com/product/dwayne-johnson-fast-and-furious-8-black-vest

    reply

  • Anonymous - 3 months ago

    Thanks for sharing your great experience with us. http://www.gulfgames.net http://www.gulfgames.net/intelligence-games/ http://www.gulfgames.net/children-games/ http://www.gulfgames.net/girls-dress-up-games/ http://www.gulfgames.net/mario-games/ http://www.gulfgames.net/barbie-games/ http://www.gulfgames.net/make-up-games/ http://www.gulfgames.net/adventure-games/ http://www.gulfgames.net/win-million-game/ http://www.gulfgames.net/ben-ten-10-games/ http://www.gulfgames.net/friv-games/ http://www.gulfgames.net/cooking-games/ http://www.gulfgames.net/girls-games/ http://www.gulfgames.net/flash-games/ http://www.gulfgames.net/action-games/ http://www.gulfgames.net/girls-dress-up-games/ http://www.gulfgames.net/war-games/ http://www.gulfgames.net/car-games/

    reply

  • cellulite - 2 months, 4 weeks ago

    Cellulite is most cellulite destroyer review noticeable on people who are overweight. Incorporating a consistent workouts that includes swimming, yoga, jogging, http://www.cellulitedestroyerreview.com/

    reply

  • Raj Solanki - 2 months, 3 weeks ago

    I am pretty impressed with useful post. Thanks for sharing your knowledge with us.

    <b><a href="http://bookmandir.com/">Buy Books Online India</a></b>

    reply

  • website - 2 months, 3 weeks ago

    Always Dong best. I think you guys are missing Barry's point. <a href="http://tedwed.com/product/chris-pratt-the-magnificent-seven-jacket/">website</a>

    reply

  • website - 2 months, 3 weeks ago

    http://tedwed.com/product/chris-pratt-the-magnificent-seven-jacket/

    reply

  • Mark Melton - 2 months, 2 weeks ago

    <a href="http://onhaxnet.com/edius-pro-8/">EDIUS Pro 8</a> is a video editing software. It the is the perfect finishing tool for professional productions, including documentary and 4K theatrical productions.

    reply

  • Zachary Rutled - 2 months, 2 weeks ago

    EDIUS Pro 8 is a video editing software. It the is the perfect finishing tool for professional productions, including documentary and 4K theatrical productions. http://onhaxnet.com/edius-pro-8/

    reply

  • belly breakthrough - 2 months, 2 weeks ago

    I'm speaking about the paper, here, people, and face it'no matter just how much you like stuffed,. Lean belly breakthrough review

    reply

  • Shawar Ali - 2 months, 1 week ago

    https://celebskool.com/shawar-ali-wiki-profile-career-height-bio-age-dob-wallpaper/

    reply

  • Anonymous - 2 months, 1 week ago

    صور بنات صوربنات

    reply

  • memo - 2 months, 1 week ago

    تحميل برامج مواقيت الصلاة مواقيت الصلاة القاهرة مواعيد الصلاة

    reply

  • ledo - 2 months, 1 week ago

    برامج

    برنامج الاذان

    مواقيت الصلاه

    ماسنجر

    reply

  • SteveErvin - 2 months ago

    Django settings for static resources can be somewhat hard to design and investigate. Notwithstanding, in the event that you simply add the accompanying settings to your settings.py, everything ought to work precisely obviously. More established renditions of Django won't naturally make the objective registry (STATIC_ROOT) that collectstatic utilizes, <a href="http://www.aoneassignments.com/pay-to-write-essay">pay to write essay</a> in the event that it isn't accessible. You may need to make this registry in your codebase, so it will be accessible when collectstatic is run.

    reply

  • SteveErvin - 2 months ago

    Django settings for static resources can be somewhat hard to design and investigate. Notwithstanding, in the event that you simply add the accompanying settings to your settings.py, everything ought to work precisely obviously. More established renditions of Django won't naturally make the objective registry (STATIC_ROOT) that collectstatic utilizes, [url=http://www.aoneassignments.com/pay-to-write-essay]pay to write essay[/url] in the event that it isn't accessible. You may need to make this registry in your codebase, so it will be accessible when collectstatic is run.

    reply

  • SteveErvin - 2 months ago

    Django settings for static resources can be somewhat hard to design and investigate. Notwithstanding, in the event that you simply add the accompanying settings to your settings.py, everything ought to work precisely obviously. More established renditions of Django won't naturally make the objective registry (STATIC_ROOT) that collectstatic utilizes, pay to write essay in the event that it isn't accessible. You may need to make this registry in your codebase, so it will be accessible when collectstatic is run.

    reply

  • Cherry - 1 month, 3 weeks ago

    Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. E-commerce Firesale Review New Training Course QIC review Course about COPYWritting Marketer Live Review Social Media Tool Octosuite Review

    reply

  • Anonymous - 1 month, 3 weeks ago

    http://www.gamesx90.com/intelligence-games

    http://www.gamesx90.com/girls-games

    http://www.gamesx90.com/adventure-games

    http://www.gamesx90.com/mario-games

    http://www.gamesx90.com/car-games

    http://www.gamesx90.com/cooking-games

    http://www.gamesx90.com/action-games

    http://www.gamesx90.com/war-games

    http://www.gamesx90.com/barbie-games

    http://www.gamesx90.com/makeup-games

    http://www.gamesx90.com/dressup-games

    http://www.gamesx90.com/win-million-game

    http://www.gamesx90.com/ben-10-games

    http://www.gamesx90.com/friv-games

    reply

  • Mark Thompson - 1 month, 2 weeks ago

    ecommerce Firesale review

    reply

  • yakuza4d.com - 1 month, 1 week ago

    She told me she just didn’t see herself as a leader and didn’t realize that other people at the school saw her as a leader as well http://dokterpoker.org/app/img/peraturan.html http://dokterpoker.org/app/img/jadwal.html http://dokterpoker.org/app/img/promo.html http://dokterpoker.org/app/img/panduan.html http://dokterpoker.org http://633cash.com/Games http://633cash.com/Pengaturan http://633cash.com/Daftar http://633cash.com/Promo http://633cash.com/Deposit http://633cash.com/Withdraw http://633cash.com/Berita http://633cash.com/Girl http://633cash.com/Livescore http://raksasapoker.com/app/img/peraturan.html http://raksasapoker.com/app/img/jadwal.html http://raksasapoker.com/app/img/promo.html http://raksasapoker.com/app/img/panduan.html http://raksasapoker.com/ http://yakuza4d.com/peraturan http://yakuza4d.com http://yakuza4d.com/home http://yakuza4d.com/daftar http://yakuza4d.com/cara_main http://yakuza4d.com/hasil http://yakuza4d.com/buku_mimpi http://dokterpoker.co/app/img/peraturan.html http://dokterpoker.co/app/img/jadwal.html http://dokterpoker.co/app/img/promo.html http://dokterpoker.co/app/img/panduan.html http://dokterpoker.co http://www.cintaberita.com http://www.cintaberita.com http://www.cintaberita.com http://www.cintaberita.com http://www.cintaberita.com http://beritamedannews.blogspot.com http://beritamedannews.blogspot.com http://beritamedannews.blogspot.com http://beritamedannews.blogspot.com http://beritamedannews.blogspot.com

    reply

  • Anonymous - 3 weeks, 3 days ago

    Obat Penurun Trigliserida Obat Tradisional Alami Penyakit Trigliserida amazon Plus dapat menyehatkan penyakit trigliserida serta sangat aman jika digunakan & tidak akan menimbulkan efek samping bagi yang menggunakannya. Amazing Plus Obat Tradisional Alami Penyakit Trigliserida

    Obat Jantung Lemah amazon plus Jus Kulit Manggis adalah Obat Tradisional Alami lemah jantung yang begitu aman diminum & tanpa efek samping. amazon Jus Herbal diracik dari bahan-bahan alami yaitu sari kulit buah manggis, buah bunga rosella, apel, buah anggur & mengunakan madu digunakan sebagai pengawet alaminya.

    Obat Tradisional Vertigo pemulihan Vertigo dengan Obat tradisional Vertigo Alami Yaitu Obat Herbal Amazon Plus. buah manggis yang adalah kandungan pada Obat Penyakit Vertigo Obat Herbal Xamthone, terdapat zat antioksidan yang sangat tinggi melewati berlipat-lipat kekuatan vitamin C dan E. Guna antioksidan tersebut dapat menjelajah ke seluruh tubuh, menormalkan radikal bebas, sehingga tubuh supaya lebih bersih dan sehat. Antioksidan juga bersifat sebagai anti mikroba, antiviral, antiparasit, dan membantu mengatasi tekanan darah rendah, menjadikan kekuatan tubuh pada penyakit, melindungi hati, antidepresi, antitumor, dll. Kandungan bunga rosella dan madu murni didalamnya menghasilkan Obat tradisional Vertigo ini lebih sempurna dan berkhasiat. Karena bunga rosella sangat berperan aktif dalam menyembuhkan Vertigo.

    reply

  • Prio - 2 weeks, 3 days ago

    This is a good content having well-scripted, appealing written content that may be brimming with initial and wise sights jual besi cnp murah jual genset malang distributor besi baja jual genset malang jual ranka atap galvalum distribut baja wf hbeam jual plat besi murah jual parfum choirose ori jual payung murah grosir konveksi kaos surabaya jual payung lipat grosir staedtler pensil terbaik

    reply

  • Mark Thompson - 2 weeks, 1 day ago

    Video Wave Review

    Video Wave Review

    Video Wave

    Video Wave Bonus

    Video Wave Pro Review

    reply

  • Jax Proster - 5 days, 16 hours ago

    This is my first time I visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! Keep up the good work. Thanks once again. AutoViral Review l Video Spin Blaster Pro 2 Review l MemberPal Review

    reply