Heroku : Python Flask App with Redis

In this tutorial we will learn how to build a simple Hello World Flask App and deploy to Heroku

Pre-Rerequisites

Make sure you have Python 2.x installed on the machine. Also, install the Heroku Toolbelt

Also install pip tool, pip is a PyPA recommended tool for installing Python packages. More information to install pip can be found at pip installation.

Install Virtual Environment

Create a folder flask-hw-sample and install a virtualenvironment in it. We are using virtualenv to create the environment and then actuvate it with the command source venv/bin/activiate.

Note

virtualenv is a tool to create isolated Python environments. The problem being addressed is one of dependencies and versions, and indirectly permissions. If you want to install an application and with dependencies. If an application works, any change in its libraries or the versions of those libraries can break the application.

It is also useful f you can’t install packages into the global site-packages directory, for example, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

$ mkdir flask-hw-sample
$ cd flask-hw-sample
$ virtualenv venv
$ source venv/bin/activate

Install Dependencies

Our application need flask and guncorn libraries which can be installed using pip.

$ pip install flask gunicorn

Creating a Simple Flask App

  1. First Create a base Flask app with simple REST endpoint/ in a file app.py in the folder created above.

    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    if __name__ == '__main__':
        app.run()
    
  2. Run the app using the following command

    $ python app.py
    

    Your app should now be running on localhost:5000

Git Ignore

Add a .gitignore file to the base directory so that venv and other unnecessary files are not checkedin.

  1. Initialize the file
$ vi .gitinore
  1. Content of the file will be similar to listing below
venv
*.py~
  1. Save the file

Initialize git

Initialize the git repository as shown by commands below.(We are assuming you have git already installed on the machine)

$ git init
$ git add .
$ git commit -m "initial commit"

Create a Requirements File

Requirements file is needed for heroku to detect that this a flask app and also install appropriate python packages, flask and gunicorn in our case.

$ pip freeze > requirements.txt

Create a Procfile

Create a file name Procfile in the root of the app and add following content. This specifies that the app uses a web dyno with gunicorn as http server.

web: gunicorn app:app --log-file -

Deploying to Heroku

Deployement is being done in three commands listed below.

1. Create a heroku app, this create a git remote with name heroku 2 Do a git push to heroku remote created by the command above. 3. Open the app in a browser with command verb|$ heroku open|

$ heroku create rd-flask-hw
$ git push heroku master
$ heroku open

Configure Add-On Redis

$ heroku addons:create rediscloud

Modify App

We will modify the app to include logic for setting and getting username from Redis.

  1. Instantiate redis from the Environment variable REDISCLOUD_URL
  2. Add a new function setname(name) where the name will be passed from the URL. Set the name in redis using key 'name'
@app.route('/')
def hello_world():
  name=db.get('name') or'World'
  return 'Hello %s!' % name
  1. Modify hello_world() function to query the name with the key 'name'

    @app.route('/setname/<name>')
    def setname(name):
        db.set('name',name)
        return 'Name updated.'
    

Full Code Listing

import os
import redis
from flask import Flask

app = Flask(__name__)
db=redis.from_url(os.environ['REDISCLOUD_URL'])


@app.route('/')
def hello_world():
    name=db.get('name') or'World'
    return 'Hello %s!' % name

@app.route('/setname/<name>')
def setname(name):
    db.set('name',name)
    return 'Name updated.'

if __name__ == '__main__':
    app.run()

Update the Requirements File

$ pip install redis
$ pip freeze > requirements.txt

Commit and Deploy

$ git add .
$ git commit -m "added redis”
$ git push heroku master
$ heroku open

Summary

In this tutorial we learnt how to create a simple Python Flask app and deploy it on Heroku.