Flask Biography Tutorial Part III : Application Scratch and Creating Local Working Environment

Python virtual environment
Contained all your Pythons library and framework inside a sandbox, ... and you are ready to play!

Now that we have a clear understanding of what the application that we are going to build, we can directly start our code. I am going to use bio as the project name of our application. If you haven't create it, you can follow the first series of the article here. From inside bio folder you will find several files and folders. For starter, lets open the file setup.py and inspect its contents :

from setuptools import setup
setup(name='YourAppName',
version='1.0',
description='OpenShift App',
author='Your Name',
author_email='example@example.com',
url='http://www.python.org/sigs/distutils-sig/',
#      install_requires=['Django>=1.3'],
) 
 

Openshift use setuptools to package application and manage its dependency. Now that we know what technology we are going to use, let's modify it as follows :

from setuptools import setup
setup(name='Bio',
version='1.0',
description="Let's you have a fully interactive Curriculum Vitae",
author='Eko S. Wibowo',
author_email='swdev.bali@gmail.com',
url='http://www.python.org/sigs/distutils-sig/',
install_requires=
[
'Flask==0.10.1',
'Flask-SQLAlchemy==1.0',
'Flask-Login==0.2.7',
'Flask-WTF==0.9.2'
],
)

You can see that we include several libraries that we need. And beside that, we also include its version number. It will make push-ing the code to Openshift slightly faster, as it will not try to get the latest version of the library. This mean, you can safely remove the version and inspect what version Openshift currently use. After that, you can return to your setup.py and modified it accordingly. That's exactly what I did!

Now that you have made changes to the code, you can experimenting updating your application in Openshift. It really is an enjoyment doing this. Just issue these git command :

git add .
git commit -am'commit comment'
git push

DONE Cool

You can see Openshift display various system message that you can study to gain better understanding of the application startup process. But of course nothing change if you try to open your application from web browser (mine is located in http://bio-ekowibowo.rhcloud.com)

Before coding for our Flask application, first we must setup a virtual environment for our Python Flask application. Think of a virtual environment as a safe sandbox where our application can run. Each application that you develop should maintain its own complete set of libraries that it use. Fail to do this, it's likely that your application can break if another application update the same library to the newer version. Also, it lets you run your application locally but in the same environment as it is in Openshift environment.

If you work on Windows environment, this article will give you a clear way of setting up Python environment for you. But, if you are in Linux Ubuntu, you can directly install virtualenv this way :

$ sudo apt-get install python-virtualenv

And from within bio directory, create a virtual environment and activate it :

$ virtualenv env
$ source env/bin/activate 

This will create an env directory from within bio directory, where all python packages for your application will be installed. Activating a virtual environment make sure that the python binary inside your virtual environment is the one that's going to be executed when you issue python command.

Our next step is to install all libraries that our bio application depends on. We use pip to install dependencies defined in setup.py, with added dependency for psycopg2 which is python driver for PostgreSQL database.

$ pip install Flask==0.10.1
$ pip install Flask-SQLAlchemy==1.0
$ pip install Flask-Login==0.2.7
$ pip install Flask-WTF==0.9.2
$ pip install psycopg2

Up until now, we already have a perfect working environment whether it's locally using virtual environment or remotely in Openshift. That's good!

As you already read from my previous article, saying that a Flask application can lived within a single *.py file, well, that's exactly what I am going to show. Or to be precise, at first we just use this single main.py file to hold all of our application code. Later when all the application parts established, then we will move them into separate *.py file. Where do you put this main.py file? Inside wsgi folder. All of your application code will reside in this wsgi folder. Now, here is the simplest Flask application that you can build :

from flask import Flask
application = Flask(__name__)
if __name__ == '__main__':
  application.run(debug=True, host="0.0.0.0", port=8888)

I intentionally gave the name of our Flask object as application, as it is required by Openshift to run our application properly. I hope the code quite self-explanatory. Which is first we import Flask class from flask package. And then instantiating our single and only Flask object named application. And if this file run from the shell, we run our flask application using host address of "0.0.0.0", which will lets your application be accessed from outside world. You can run this application from the shell using the command :

$ python wsgi/main.py

Try opening this application from your browser using the address localhost:8888. Do you get an error message like this : "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." ? No problem. Let's start defining our first route

Route is the cornerstone of every Python web application. There is another (and more common) term for route which is view. Route/view in a web application is the endpoint in your application code that get executed when certain URL is requested by user. In our current application, we don't define any route/view yet. Let's define it now :

from flask import Flask
application = Flask(__name__)
@application.route('/')
def index():
  return "Hello World!"
if __name__ == '__main__':
  application.run(debug=True, host="0.0.0.0", port=8888)

If you have no error when saving main.py, you can just refresh your browser to see that the code changes take effect immediately. But if there is error, the server will stop and you have to run your server again. Now your browser should display something like this :

 

Flask with one route
A working Flask application with only single route/view

 

The code is not yet complete. You have to told Openshift, that you already have a new application object. Openshift use wsgi/application script to start your application. Change all of its line to be like below :

#!/usr/bin/python
import os
virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
  execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
  pass
from main import application

Do a comparison with the original application script, and you can find that we only add the last line to the existing script

Before commiting and pushing this code to Openshift, you may want to use a .gitignore in the root directory of your bio application. Use this gitignore, renamed it into .gitignore and add this line as the first line in that file :

env/

This will make sure that your local virtual environment didn't get pushed to the Openshift, which is a useless process.

Great! This will conclude Part III of this articles, let me know what trouble you have in the comment section. 

Our next article will be dealing with our view in a more better way using Jinja templating, which will allow us to bring a better visual layout of our application.

Stay tuned! 

PS : You can download code for this article here : bio-part-3.zip

 




Leave comments

authimage
  • where is the wsgi folder

    • iqbal
  • Great to hear that!
    Surely that's the one that I should have added in this series. ;)

    • eko
  • Thanks for your reply,
    as it turned out, I had a problem with my ssh and couldn't git clone the app. that's why the 'bio' folder wasn't created on my local drive. after few hours of Googling and hair pulling i was finally able to fix it.

    finally, everything works. on to part IV!! :)

    • greg
  • Thanks for your reply,
    as it turned out, I had a problem with my ssh and couldn't git clone the app. that's why the 'bio' folder wasn't created on my local drive. after few hours of Googling and hair pulling i was finally able to fix it.

    finally, everything works. on to part IV!! :)

    • greg
  • Hi Greg

    If you have done rhc app-create, it will automatically create (git clone) your application to the current directory. See if you find it here :
    (a) DOS : dir bio
    (b) Linux : ls bio

    It should be there :)

    • eko
  • Hi, i've been following steps 1+2, installing rhc on my computer (windows 7) and then:
    rhc app-create bio python-2.7 postgresql-9.2. and i got a message that the app is available.

    but where can i find bio folder on my computer? i can't seem to find it anywhere.

    • greg

Copyright(c) 2014 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved