Day 3 : Flask — Instant Python Web Development with Python and OpenShift


Few days back Packtpub contacted me to review their recently published book on Flask. The book titled Instant Flask Web Development is written by Ron DuPlain. On my third day  of 30TechnologiesIn30Days challenge, I have decided to spend time on Flask. In this blog,  I will first talk about Flask framework basics and then will provide a small book review. Also, I will port the sample application to OpenShift. I am not entirely new to Flask and have built some sample applications using it. This would be a good refresher.

For people who are not following this blog, I have taken a challenge to learn 30 technologies in 30 days. Every day I will learn a new technology and will blog about it. If a technology can not be covered in a single day, I will write different topics within that technology each day.

flask-framework

What is Flask?

For fellow developers who are not aware of Flask let me give a small introduction to it. Flask is a micro framework for doing web development in Python. If we have to do web development in Python, Flask is a very good choice. By micro framework, it does not mean that we have to write all our code in a single file as recommended by other micro frameworks. Microframework refers to simplicity and small size of the framework. We can start working with simple one file structure using features we need. As we  become familiar with Flask, we can modularize the code and learn advanced  functionalities offered by Flask. Flask does not make any recommendations about any file structure but later in the blog I will talk file structure recommended in the book.

To make it more clear, lets look at the sample code.

from flask import Flask
app = Flask(__name__)

@app.route('/', defaults={'name':"Guest"})
@app.route('/' , methods=['GET'])
def say_hello(name):
    return "Hello " + name

if __name__ == "__main__":
    app.run(debug=True)

This is a very simple example but expressive. You can just sit and admire it.  Let’s decipher the code snippet shown above.

1. In the first line we imported Flask class so that we can create an instance of Flask application.

2. In the next line we created an instance of Flask class. This is WSGI application instance. WSGI stands for Web Service Gateway Interface and is the Python standard for hosting web projects. The argument tells Flask where to find application static assets and templates. In the example shown above we passed __name__ which informs Flask to use the current module to location resources.

3. Next we defined a couple of routes for “/” url. The first route is for root url ‘/’ and next corresponds to any url like /shekhar or /abc. For the ‘/’ route, we set the default name as “Guest”. If a user makes a request to http://localhost:5000/, then he will see “Hello Guest”. If a user makes a request to http://localhost:5000/shekhar, then he will see “Hello shekhar”.

4. Finally we start the development server to run the application using python app.py command. We should copy the code shown above in app.py file. We also enabled debugging by passing Debug=True. Debugging provides interactive debugger in the browser when unexpected exceptions occur. Another benefit of the debugger is that it will automatically reload the changes. We can keep the debugger running in the background and work through our application. This provide highly productive environment. Ask any Java developer about automatic reloading :).

Few things worth knowing about Flask :

1. Flask was created by Armin Ronacher in 2010.

2. Flask was inspired by Sinatra(Ruby framework to create web apps with minimum fuss).

3. Flask depends on two libraries Werkzeug(WSGI utility library for Python) and Jinja2(a templating engine).

4. Flask follows conventions over configuration and has good sensible defaults.

Why should I care?

I learnt Flask because

1. Easy to Learn : I have been a Java developer throughout my 8 years of software development. So after learning Python fundamentals I wanted to get into web development. Flask is a very easy to use and dead simple framework as I showed in my example above. It naturally fits in my mind, and I can develop faster.

2. Very active and vibrant community : I talked to few of my Python friends and everybody recommended me to start with Flask. I googled on the web and everywhere I found Flask to be the best modern Python web development framework.

3. Write REST API : I wanted to learn a framework which makes it easy to write REST services. The example shown above can very easy return json documents using Flask jsonify function. The architecture of future web applications is REST backend with the Front end written in modern JavaScript MV* framework.

4. Excellent documentation spread over 280 pages with lots of examples

5. Flask follows conventions over configuration. It has good sensible defaults like static folder for static assets. We can override most of the defaults.

Instant Flask Web Development Book Details

Now that we are on same page lets look at the book details.

1. Recipes based book where in each section you develop a sample application. The book is only 78 pages.

2. The book cost $11.

3. Book is written by Flask committer.

What I liked in book?

1. Started with virtualenv which is the correct way to work with python. It avoids polluting your main python installation. This allows us to work with different versions of python for different projects.

2. Used best practices like proper folder structure for the project. Although flask is a micro-framework, but we should define proper layout for application. This helps when developing enterprise applications.

3.The book talked about Flask functionalities and extensions that I was not aware off. The book talked about Flask-Script extension. Flask-Script provides support for writing external scripts for Flask applications.

4. The book covered WTForms in detail. WTForms helps us write form based applications.

What should have been better?

1. Some topics were not very clear and did not provide much context for beginner. I did not understand why one would use subdomains in Flask application.

2. Real database like Postgresql or Mysql were missing. Although author talked about using different database uri to connect to PostgreSQL and Mysql, but did not gave real example. I prefer when a real database is used instead of in-memory database. One advantage of using in-memory databases is that it can make things easy for beginners.

3. No talk about REST services : REST services are critical to today’s application. One of the advantage of using Flask is that we can very easily write REST services using it.

4. No talk about how one can use NoSQL database like MongoDB with Flask.

5. Flask framework has very good unit testing support, but the author did not talk about it.

6. No talk about Cloud deployment. In this blog, I will show how we can deploy the sample application discussed in the book on OpenShift.

Should I buy this book?

This book is useful for Flask beginners who want to write traditional RDBMS based web applications.

Getting Started with Flask

Before we can get started with Flask we need to install [Python](http://www.python.org/download/) and [virtualenv](http://www.virtualenv.org/en/latest/) on our machine. The Python version I am using in this blog is 2.7. To install flask do the following.

$ mkdir schedulingapp
$ cd schedulingapp/
$ virtualenv venv --python=python2.7
$ . venv/bin/activate
$ pip install flask

In the commands shown above, we first created a directory for the sample application and then activated virtualenv. The virtualenv helps avoid polluting main python installation on the machine. This allows us to work with different versions of python for different projects. Finally, we installed flask. The pip install flask will install the latest stable version of flask framework.

Deploying Sample Application to OpenShift

The sample application in the book is a simple appointment application. We can register for an account and then login to application to create, edit, and list appointments. To get the application running on the local machine, execute the commands mentioned below.

$ git clone https://github.com/shekhargulati/instant-flask-web-development-book-app.git scheduleapp
$ cd scheduleapp
$ virtualenv venv --python=python2.7
$ . venv/bin/activate$ pip install -r requirements.txt
$ python manage.py create_tables
$ python manage.py runserver

This will start the application at http://127.0.0.1:5000 and user can register an account and get started with application.

This is fine, but I want to host my application in the cloud. We will be deploying the application on OpenShift. OpenShift is an open source, public, scalable Platform as a Service.

Prerequisite

Before we can start building the application, we’ll have to do few setup tasks :

1. Sign up for an [OpenShift Account](https://openshift.redhat.com/app/account/new). It is completely free and Red Hat gives every user three free Gears on which to run your applications. At the time of this writing, the combined resources allocated for each user is 1.5 GB of memory and 3 GB of disk space.

2. Install the [rhc client tool](https://openshift.redhat.com/community/get-started#cli) on your machine. The rhc is a ruby gem so you need to have ruby 1.8.7 or above on your machine. To install rhc, just type

sudo gem install rhc

If you already have one, make sure it is the latest one. To update your rhc, execute the command shown below.

sudo gem update rhc

For additional assistance setting up the rhc command-line tool, see the following page: https://openshift.redhat.com/community/developers/rhc-client-tools-install

3. Setup your OpenShift account using rhc setup command. This command will help you create a namespace and upload your ssh keys to OpenShift server.

Deploying Application

To deploy the application on OpenShift just type the command shown below.

rhc create-app schedapp python-2.7 postgresql-9.2 --from-code=https://github.com/shekhargulati/schedapp-openshift.git

It will do all the stuff from creating an application, to setting up public DNS, to creating private git repository, and then finally deploying the application using code from my Github repository. The app is running here http://schedapp-shekhargulati.rhcloud.com/

That’s it for today. Keep giving feedback.

Shameless Plug

If you are a Java, Python, Node.js, Ruby, or PHP developer then you should take a look at OpenShiftOpenShift is a public Platform as a Service, and you can use it to deploy your applications for free.

2 thoughts on “Day 3 : Flask — Instant Python Web Development with Python and OpenShift”

    1. I have shared this with my packtpub contact so hopefully they will contact him. I am not criticizing the book. I am just sharing my expectations.

Leave a comment