Zero to Heroku with Flask

This week I tried my hand at some Python for the first time in a long time. The goal of this was to simply create a ‘Hello World!’ application on Heroku.

Linux Mint comes with Python as standard and this post will be entirely about working with Mint. The useful tools I set up are on the recommendation of ’Two scoops of Django’ and their chapter on environment setup.

First I needed pip, a package management system for software written in python. Second Virtualenv, which is used to create isolated Python environments. This addresses the same role as Ruby Gemfiles and Bundler. These two are installed with apt-get.

    $ sudo apt-get install python-pip
    $ sudo apt-get install python-virtualenv

Also recommended was the nattily named virtualenvwrapper. This can be installed in the same way but requires some further setup. To set the location of project and the python environments I had to add the following to my bash profile. 

    export WORKON_HOME=$HOME/.virtualenvs
    export PROJECT_HOME=$HOME/Devel
    source /usr/local/bin/

With this setup the project can now be started making full use of the tools installed above. Amazingly these tools mean that it is possible to have a project live on Heroku with only 10 commands from the terminal. I have split these into two groups of 5. The first being

  1. $ mkproject hello
  2. $ pip install Flask gunicorn
  3. $ pip freeze > requirements.txt
  4. $ touch 
  5. $ echo 'web: gunicorn hello:app’ > Procfile

So what happened here? mkproject is a command from virtualenvwrapper, it creates an environment called hello and and project called hello. Then it switches to the project directory and starts the created environment. Both Flask and gunicorn are python packages that we install to the enviroment. pip freeze lists all packages that are currently in use, saving them to requirements.txt allows Heroku to install the same ones. we then create an application file called and a Procfile to give instructions on starting the application.

At this point we can write an application in the file. For a quick example I just used the sample application for Heroku for getting started.

So at this point we have a working application that can be run locally with foreman. Next is to push this to Heroku. These steps should be familiar if you have previously used Heroku however I have listed them below for completeness. 

  1. $ git init
  2. $ git add .
  3. $ git commit -m 'init’
  4. $ heroku create
  5. $ git push heroku master

At this point your application is live on Heroku. Running a final 'Heroku open’ will open the application in your default browser to prove the point. 

These tools are brilliant but this is only the slimmest of introductions. For a fuller overview is this blog post.