Deploying Python and Django Apps on Heroku
Last updated 05 November 2018
Table of Contents
For a conclusive step–by–step guide on using Heroku, see Getting Started on Heroku with Python.
Expected Files for Python
Heroku knows that your app is a Python app by the existence of one of two files in the root of your application:
If one of these files aren’t present in the root of your repository, the Python buildpack will fail to detect your application.
Heroku has a few constraints that we put on your application. These constraints enhance the developer experience, allow for easy scaling, and enforce good architectural decisions. We call these constraints The 12 Factors.
Some important constraints to note:
Your application will not have access to persistent disk storage. Any changes made to the disk will be lost every time a process reboots (which is at least once every 24 hours). Disks are not shared between processes (so if you scale your
2, you’ll have two independent disks). So, if persistent storage is needed, hosted block storage is recommended, like Amazon S3 (also available as a Heroku Addon Bucketeer).
Sensitive data, such as database credentials, secret keys, etc, are to be stored in environment variables. These can be read set with the
$ heroku configcommand (
$ heroku config:set <key>=<value>). Your application should read these environment variables at runtime, instead of having these values hardcoded within the codebase.
Databases and other services (e.g. Heroku Addons) are made available to your application through environment variables. Instead of running Postgres on the same host as your application code, you attach the
$ heroku addons:add heroku-postgresql) to your application, which will automatically set some environment variables for your application to read. To access these resources locally (for development / debugging), you can see the values by running
$ heroku config -s.
Deployment of Python Applications
Deployment to Heroku is relatively straightforward. Dependencies specified in
requirements.txt are automatically installed when you deploy your application.
If you’re using Django, ‘collectstatic’ will also automatically be run for you during a deploy. This can be a bit tricky to configure properly, so we recommend that you use the Django-Heroku Python package, which will set everything up for you.
If you’d like to do something more fancy, like run 'migrate’ automatically during a deploy, check out Release Phase, which enables you to run tasks before a new release is deployed to production.
Python Versions & Upgrades
To change the version of Python being used, you can specify a Python runtime.
Once your application is deployed, you are locked in to the version of Python used when the application was created. You can update or upgrade by changing your
runtime.txt file. You will be notified, in build output, if the version of Python being used is no longer up–to–date.