Saturday, July 30, 2016

Getting Started with Python Flask

Flask is a micro-framework for seamless web application development. Its based on Werkzeug WSGI and Jinja 2 rendering engine.
The prime advantage of using flask is in its simplicity. While Django is a power packed web framework, flask relies on a sleek and minimal approach.

Agenda of this post
In this post, we will discuss how to setup flask and run a demo flask server.

Prerequisite
Familiarity with Python programming. A rudimentary idea of Web Server Gateway Interfaces (WSGI) is desired. Also, we assume that you are familiar with the web development paradigms and client-server architectures. 
Note: The code snippets and examples in this tutorial is written in Python 2.7

Environment Setup
Before beginning, make sure you have Python installed in your system. For easy installation of required packages, install pip and easy_install
You can install easy_install using the following command
$ sudo apt-get install python-setuptools
Use easy_install to install pip
$ sudo easy_install pip
Alternatively you can use apt-get to install pip
$ sudo apt-get install python-pip
Now its time to install Flask.
$ pip install Flask
For system wide installation, use
$ sudo pip install Flask

Running your First Program
Before we dig deeper into the Flask, lets try to run a demo program. 
Save the following code snippet in a file (lets say, hello.py).
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World"

if __name__ == "__main__":
    app.run()
Start the server, you will see the url where the server is running. By default the host will be 127.0.0.1 and the port will be 5000. You can stop the server anytime using CTRL+C (Be careful with this, you might end up with a zombie server blocking the port if you use wrong keyboard interrupts like CTRL+Z)
$ python hello.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Now you once you hit the url in your browser, you will see the "Hello World" message. Here is a screenshot of the demo.






We would like to stop the discussion here. In the next post, we will analyze the anatomy of this demo program so that you can start writing your own flask servers. 

No comments: