How to Install and Configure a Python Flask Dev & Deploy Environment

Why this Tutorial?

Last winter I wanted to learn a new programming language and I chose Python. I’ve been attending many Python related meetups & participating in hackathons in Philly and NYC with the intention of expanding my Python skills. As I was scouring the net for Python related tutorials and information I found lots of very useful information that enabled me to get a solid foundation of the Python language. Most of the tuts and how to’s I read were primarily related to learning and writing console applications (DOS/Terminal console apps). After feeling comfortable enough with Python I wanted to start writing web applications.

When researching how to write apps in Python I was smacked in the face with a ton of options. Unlike the console apps I was writing, it became apparent to me that writing web apps using Python is more complex and involved. I researched the more popular Python web frame works like Django, Pyramid, Flask and Bottle. I wanted to use a framework that would be easy to use/learn with as little dependencies and restrictions as possible. After all my research and experimenting I chose the Flask framework as my weapon of choice. It has a small foot print and decent documentation.

After I picked Flask as my web framework I realized that I needed a place to host my app online. Normally I would just spin up a virtual server on my private virtual host and create a new instance of Apache on a Linux server that I would have to manage and maintain for the life of my app. I’ve been in the IT game for quite some time now and I’m definitely not down with adding or managing anymore servers than I already have. Coincidentally I met two very friendly and helpful RedHat developer/evangelists at a hack-a-thon in NYC and they introduced me to their Platform as a Service (PaaS) called OpenShift. If you don’t know and are asking yourself: What is OpenShift? – it allows developers and software engineers to basically create virtual servers, deploy and host their apps on the web. Best of all it’s free and it’s compatible with many of the current open source programming languages, frameworks and databases. This service is great for devs like me who don’t want to perform double duty as sys admin and developer. OpenShift takes care of the system administration which frees you up to focus on your apps. Anyway we will use OpenShift to host our app in this tutorial.

Now that OpenShift became the home for my app I needed to start learning Flask. I found very little tutorials that covered Flask and they were all written by developers which in my opinion tend to assume the readers have more knowledge then they actually do. The fire ignited and I decided to write a grassroots tutorial for people like myself that want to learn how to write web apps in python and host it on a PaaS like OpenShift.

Let’s Get started – Prep Our Dev Box for some PaaS action

Now we need to prepare our box but before we start there are a few things I assume that you are familiar with.

  • You will need an active internet connection
  • This tutorial assumes you are using a Linux OS (I prefer one of these Fedora, Debian or Ubuntu).
  • You know what a terminal, console, command line is. Also when I list commands for you to run in the console the $ symbols should not be typed or included in the command, it just represents the bash prompt.
  • You should have a very basic understanding of the GIT version control system and how to use it. Use the GIT Docs or this tutorial to learn basic GIT commands. More importantly learn what version control is. Plenty of GIT material on the web, so do a search.
    I assume that you have a basic understanding of programming in Python, HTML, CSS & JavaScript (JavaScript not so important for this tut) if you’re not too familiar then click the links and learn em.

Now let’s get on with it.

Create your app’s home in the “Cloud” using the OpenShift PaaS

  • Create your FREE OpenShift account Here Very simple sign-up email + password only
  • Install the OpenShift Client Tools. Use these directions for your particular Operating System these tools have a command line interface and allow more control over your app. The OpenShift tool requires an installation of Ruby.

When installing Ruby on Linux I recommend that you use the Ruby Version Manager instructions that I wrote in the Other Sources of Reference Material section at the bottom of the page.

Run these commands in the terminal:

$ rhc domain create -n DomainName -l EmailAddress -p password

Create a namespace (a sub domain) for your app and replace the values with your information

$ rhc app create your-apps-name python-2.6

Create your app using the python template. Replace the bold bits with your information

$ cd your-apps-name

Change directories into your newly created application folder your-apps-name

$ git remote add upstream -m master git://github.com/openshift/flask-example.git

Add the upstream repository address to your local git config

$ git pull -s recursive -X theirs upstream master

Get the quick start code from the OpenShift repositories

$ git push

Push your newly created Flask application shell to your OpenShift server.

Here you want to check out your app using the url which will look similar to:

http://your-apps-name-DomainName.rhcloud.com

Technically you have a functioning Flask application up and running in the “Cloud” but we’re not done yet.

Let’s configure Python & Virtualenv on our dev box

In the last section you created and configured the base of your Flask application on OpenShift. Now you have to ensure that you have a Python installation that is compatible with OpenShift. At the time this tut was written OpenShift only supports Python 2.6. I believe that newer versions will be supported in the near future but for now we are going to use Python 2.6.

Currently I’m using Ubuntu 12.04 as my operating system and as of 12.04 the default version installed is Python 2.7. If you are using an older version of Ubuntu you can do $ sudo apt-get install python2.6 to install that version of Python.

I actually prefer to use Virtualenv to isolate my Python development environments. It’s a tool that allows you setup an isolated, self-contained Python environment in a folder on your dev box. This way you can experiment with various versions of Python without affecting your system wide configurations.
We are going to install virtualenv on Ubuntu. If you are using a different Linux distro or operating system then do a web search and find installation instructions for your specific operating system. Since my distro doesn’t have official Python 2.6 packages I had to get a community ported package of Python 2.6 that works on Ubuntu 12.04. Follow these instructions if you are running Ubuntu 12.04 or higher:

Install Python2.6 & virtualenv on Ubuntu 12.04

$ sudo add-apt-repository ppa:fkrull/deadsnakes

Install the PPA

$ sudo apt-get update

Run Update

$ sudo apt-get install python2.6 python2.6-dev

Install Python2.6

$ sudo apt-get install python-virtualenv

Install the virtualenv package

$ python2.6

This command will open the python console and you can verify that Python version 2.6 is installed

Press Control +D keys to quit python

Create & configure your local virtual Python dev environment

Do Not use sudo commands here! These commands should be executed with normal user creds.

In the terminal console type:

$ cd your-apps-name/wsgi/

Change directories to the OpenShift Flask app folder you previously created. The wsgi folder is where our app will live on OpenShift.

$ virtualenv venv --python=python2.6

Creates a folder named venv in the root of your flask app folder that houses your dev environment for this app

$ . venv/bin/activate

Activates your virtual environment for that folder.

Note: You must run this command to activate you virtual dev environmental. Fortunately you only have to run it once per terminal.

You should now have a terminal prompt that looks similar to this:

(venv)amr@mybox:~/your-apps-name$

If you see the (venv) bit in your console
prompt you are now in virtual mode and are now ready to install locally Flask and other Python related dependencies.

Install Flask into your local virtual dev environment

Now that you have your virtual dev environment active we can have some fun and install your Flask framework to our local environment.

Run this command in a terminal console:

$ pip install flask flask-wtf flask-babel markdown flup  

It will install the multiple packages separated by spaces. You will see the packages being downloaded and installed into your local dev environment. These packages are actually being installed into the venv folder that was generated earlier.

Install Flask & dependencies to our OpenShift app

OpenShift uses GIT to deploy apps into your live website. You have your dev box configured with all the Python and Flask packages that you need but now we must config your OpenShift environment so that it also has the packages you just installed. OpenShift uses a setup.py file to configure your app. The setup.py file is where we will list the flask packages that we want to install in our OpenShift gear.

$ cd ..

Changes directory into the root of your-apps-name folder

Use your fav text editor and open the setup.py file found in the root of your apps folder and make the installs_require line look like the example below:

from setuptools import setup  
setup(name='ws',
    version='1.0',
    description='just an app',
    author='me',
    author_email='me@gmail.com',
    url='http://www.python.org/sigs/distutils-sig/',  
    install_requires=['Flask','flask-wtf','flask-babel','markdown','flup'],
)

Save the setup.py file. The key attribute that we are concerned with is the install_requires=['Flask>=0.9','flask-wtf','flask-babel','markdown','flup'],. The install_requires attribute is a simple array list of strings that represent python modules that your app needs. If you need other modules that are not listed you can just add another element to the file. The setup.py installs the dependencies listed as is the automated way of installing modules. It is equivalent to the pip install commands that were previously used.

Configuring your local GIT repo to ignore

Next we need to tell GIT to ignore our local venv folder so it doesn’t get uploaded to our OpenShift repository. Using your fav text editor open the .gitignore and change the contents of your file to match the following:

venv/
.project
*.pyc
*.pyo
*~

Save the .gitignore file. The .gitignore file tells git to ignore all the folders, files and file types that are listed in it.

App folder structure

Let’s create the basic folder structure for our app. In the terminal type these commands:

$ cd your-apps-name/wsgi/

Change directories into the root of wsgi

$ mkdir app

The app folder is where we will put our application package

$ mkdir app/static

The static sub-folder is where we will store static files like images, javascripts, and style sheets

$ mkdir app/templates

The static sub-folder is where we will store static files like images, javascripts, and style sheets

$ mkdir tmp

The templates sub-folder is obviously where our templates will go

$ cd app

Change into your app directory

Create our “Hello World”

I hate “hello world” apps but they are a necessary evil for now. Now you will create a __init__.py file. The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package.

Anyway, in the root of your app folder create a file named __init__.py so populate & save it with the following code:

from flask import Flask  
app = Flask(__name__)  
from app import views

The script above simply creates the application object(class Flask) and then imports the views module, which we haven’t written yet.

Create a file named views.py in your app folder. Populate & save it with the following:

from app import app
@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"

Views are the handlers that respond to requests from web browsers. In Flask views are written as Python functions. Each view function is mapped to one or more request URLs. This view returns a string, to be displayed on the client’s web browser. The two route decorators above the function create the mappings from urls / and /index to this function.

$ cd ..

Change directories into the root of wsgi where we need to modify a file a create a new one.

Let’s finish this & get Hello World running locally. In your wsgi folder there is a file named application, which was created by OpenShift. Open it with your editor, replace all of its contents with this code:

#!/usr/bin/python
import os
virtenv = os.environ['APPDIR'] + '/virtenv/'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
    execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
    pass
from run import app as application

The application file is required by OpenShift and it basically calls the run.py file that you are creating next.
In the root of wsgi create a script called run.py and save it with this code:

from app import app
if __name__ == "__main__":
    app.run(debug = True) #We will set debug false in production 

The script simply imports the app variable from our app package and invokes its run method to start the server. The app variable holds the Flask instance, we created it above. Now we can run and test our app locally. Run the following in terminal:

Note: make sure your (venv) is active in your command prompt

$ python run.py

You should see something like the following in the terminal:

* Running on http://127.0.0.1:5000/
* Restarting with reloader

You’ve just created a local instance of your web application which is only accessible from your dev box. Let’s view your new app in a browser. In a browser paste:

http://localhost:5000/index

Here you should see "Hello World" in the browser. Kool Huh? Well not really but you now have a working flask website being served locally on your dev box. This is great but our ultimate goal is to share this creation with the world online. Now we have to deploy this app to our OpenShift gear.

Ready???

Deploying to OpenShift

So you’ve got this simple flask app running on your local box and that’s awesome but we need to get it on the web. This is going to be very easy so open a terminal and get to typing.

Before you proceed it’s important the you are in the root of your app so type:

$ cd your-app-name

$ git add .

$ git commit -a -m "Initial deployment of this app to the web"

$ git push

That should do it! When the OpenShift processes are complete your app will be live on the web.
In a browser put your app’s url to see it:

http://your-apps-name-DomainName.rhcloud.com

Summary

You now have your local development and OpenShift environments configured. These separate environments will allow you to develop and test your apps locally before publishing online. Once you’ve tested and vetted your app you can easily deploy it to your live OpenShift gear on the web.

More expansive tutorials to follow

This was a long tutorial but most of the actions we performed will only have to be completed once. I intend to write follow-up tutorials that expand on how to build apps in flask and using OpenShift to serve up your apps but for now enjoy

Categories
Python
Tags
Comments are closed.