This blog fills in the blanks for people building apps for Heroku in Python. The online documentation starts from an existing repo and misses a few steps for those who already have a repo or are building from scratch.

The first concept to grasp is that you need to be working in a virtual environment locally if you want to transition to Heroku smoothly. The reason is that your local environment already has access to all of the installed modules you are using. By creating a virtual environment you ensure that all the modules you need are installed in a way that signals to Heroku to install them as well. To do that, you are going to need pipenv, which you might not have already

% pip install pipenv

To get into this env

% pipenv shell

Now you are working in the same env that Heroku would work in. Now let's install the modules you need for your app. Just go to your Python file(s) and copy out the "froms" and "imports" and install them here.

% pipenv install [space-separated list of your modules]
% pipenv install flask sklearn [etc ...]

Doing this will create a Pipfile. When pushed to Heroku, this tells the Heroku system to install the modules with pip. You can also make a requirements.txt file *instead, but I recommend against it. Using pipenv install ensures that you have a managed Pipfile and also creates a lockfile.

One other key file you'll need is a Procfile. This tells Heroku what to run on boot. For web apps, use pipenv to install gunicorn and add this line to your Procfile file

web gunicorn api:app

Where "api" is the name of the Python file to route traffic to.

Now let's set up Heroku and your repo. If you have a repo, great. Skip ahead to the next step. If not:

% git init
% git add [some files]
% git commit -m "Initial commit"

Now let's set up Heroku. You're going to need the "heroku" command locally, so if you're on a Mac:

% brew install heroku

With Heroku, log in.

% heroku login

This will ask for your email and password. Let's create a Heroku app and add the git remote:

% heroku create

You can specify your own app name by adding it as the first argument after "create."

Now the fun part. Push to Heroku and launch the app.

% git push heroku master

The output will tell you how it went. Scan what you see for errors like missing modules or a web server crash. The most common issue is a missing modules. Just go back to pipenv and add it. Then git add Pipfile and push to Heroku again.

Part of the output will be the URL to test.

If something goes wrong, take a look at the Heroku logs like this:

% heroku logs

If your web server needs to be restarted or started for the first time:

% heroku ps:scale web=1

Good luck and have fun!

Caxy Interactive is a Custom Software Development Company

See what other services Caxy has to offer.