Sunday 21 October 2012

Creating a heroku python app on windows 7

Here are the steps I follow to create a new python app on heroku. I am writing them down so that I don't have to remember them, or where to find them. I give credit to the tutorial over at "Getting Started with Python on Heroku" where I learned these steps. However these steps are tailored to windows and my way of doing things.

These instructions assume that you have set up the heroku tools and have an account, also that you have python 2.7 and the virtualenv package installed. See the notes below to links on how to set these up.

  1. Create the directory where you want to develop the app itself. I use d:\heroku\<app_name>
    For example:
    d:\heroku\exampleherokuapp
  2. Create a virtual python environment with virtualenv
    %PYTHON_PATH%\scripts\virtualenv venv
  3. Activate the virtual environment and install flask
    venv\scripts\activate
    pip install flask
    
  4. Initialize a git repo in the new directory with:
    git init
  5. Create the app with the heroku toolbelt, you can specify a name for the app or just let heroku assign one, I usually just let heroku assign one at this stage, you can change it at a later date if you need to.
    heroku apps:create
    This will create a remote repo for git called heroku

  6. Create the minimal files required to run an app.
    These are:
    • Procfile
      This is the file that tells the heroku app what to run, find out more here. In this case we just want a simple web dyno running our server. It needs just one line:
      web: python server.py
    • requirements.txt
      This is the pip requirements file that heroku uses to install the correct python packages. It can be generated with the commandline:
      pip freeze > requirements.txt
      For a simple flask app the file looks like:
      Flask==0.9
      Jinja2==2.6
      Werkzeug==0.8.3
      
    • server.py
      This is the python script that runs the server on the heroku instance. For this example lets just have it return "hello world" from the index page. The file looks like:
      import os
      from flask import Flask
      app = Flask(__name__)
      
      @app.route("/")
      def hello():
          return "Hello World!"
      
      if __name__ == "__main__":
          port = int(os.environ.get('PORT', 5000))
          app.run(host='0.0.0.0', port=port)
    You can find these files on git hub at https://github.com/bobbynewmark/exampleherokuapp

  7. Now add the files to git
    git add *
  8. Now commit the files
    git commit -m "Add the minimal required files
  9. Now push the files to the heroku instance
    git push heroku master
  10. The app can now be opened by using the open command
    heroku apps:open
    or run locally with
    foreman start
Notes