Yesterday 6th June, I participated in a tutorial session on Flask, via google hangout (What happened to the chat option?). Ramaseshan arranged the session; he invited Abhinav a flask user, as the speaker. What is Flask?

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. And before you ask: It’s BSD licensed!

It is a lightweight web framework for people who think Django is a way too complicated tool for the job. Most of my code in Deep learning is exclusively written in python (numpy, theano, keras, scipy). I am currently building a Dialogue system based on Seq2Seq architecture. I would like to run it as a chatbot and serve multiple clients. And I don’t want to get too deep into the “web” side of things. Hence, Flask is an ideal tool for me.

Abhinav covered the following topics in yesterday’s session.

  1. Getting the Hello World Application running
  2. Serving static files
  3. Rendering Templates
  4. Receiving URL encoded parameters
  5. Basic Authentication System

I would like to add the installation procedure that I had to go through before getting started with hello world.

Setting up Flask in Virtual Environment

# instructions for debian system
# install virtualenv 
sudo apt-get install python-virtualenv
# check version, mine is 15.0.1
virtualenv --version
# create a folder where you will store your projects
mkdir .flaskenv && cd .flaskenv
# create virtual environment "flask-env"
virtualenv flask-env
# activate virtual environment
source flask-env/bin/activate
# now we are in the virtual environment, lets install flask
pip install Flask

We have successfully installed flask in a virtual environment. Now lets jump to the hello world application.

Hello World!

Create a file helloworld.py. Copy paste the following code into it. And run it.

from flask import Flask

app = Flask(__name__)

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


if (__name__ == "__main__"): 
    app.run(port = 5001) 
# run it
python helloworld.py
# * Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)

When you load localhost:5001 in your browser, you will see a page with “hello world” in it.

The code is fairly simple; the imports, main function, flask app intitialization and routing. @app.route(“/”) runs the function hello( ) whenever a user loads the root address, that is localhost:5001/.

Serving Static Files

In this section, we will be serving a file app.js. Create a directory static, where all the static files will go. Create app.js inside static/.

# create a file app.js inside directory static/
mkdir static && cd static
touch app.js

Copy paste the alert call into app.js.

alert("you are feeling app.js!");

Add static_url_path=”/static” parameter to Flask( ) constructor in line 3 of helloworld.py. Run helloworld.py. Access the path http://localhost:5001/static/app.js in your browser. It should display the contents of app.js.

# Line 3
app = Flask(__name__,static_url_path="/static") 

Rendering Templates

When we have the need to render html pages/templates, we can use the function render_template( ). Create a folder templates. Create a html file index.html inside it.

<h1>A HTML File from templates/</h1>
<script src="static/app.js"></script>

Notice that we have embedded our javascript file app.js inside it.

To render index.html, the function hello() should return render_template(“index.html”).

from flask import Flask, render_template
app = Flask(__name__,static_url_path="/static") 

@app.route("/") 
def hello(): 
    return render_template("index.html")

When you access localhost:5001, you will see the heading “A HTML File from templates”, along with an alert that says “you are feeling app.js!”.

Receiving URL encoded parameters

In order to process requests with parameters encoded in the url, we need to setup the corresponding route and the parameters are provided to a function that handles it.

# GET
@app.route("/user/<username>") 
def name(username): 
    return "User %s " % username

The snippet above handles the url “/user/", where "username" is a parameter passed by the user. This variable is passed to the "name()" function which handles it. In this case, we just display the variable in the browser. Try it out for yourself.

Basic Authentication System

Sometimes we need to authenticate a user before serving him. Follow the code below carefully.

from flask import Flask, render_template, request, Response
from functools import wraps

app = Flask(__name__,static_url_path="/static") 

def check_auth(username, password):
    return username == 'admin' and password == 'secret'

def authenticate():
    # 401 response
    return Response('Could not verify your access level for that URL; \n You have to login with proper credentials',
            401,{'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    # f -> function being decorated
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args,**kwargs)
    return decorated

@app.route("/") 
@requires_auth
def secret_page(): 
    return render_template('index.html')


if (__name__ == "__main__"): 
    app.run(port = 5000) 

## Reference
# 1. http://flask.pocoo.org/snippets/8/
##

require_auth( ) is a decorator which takes the function secret_page( ) as input and returns a replacement function. To put it simply, we check if the user is already authenticated. If he is, index.html is rendered. If not, we ask for user credentials (username and password). If username and password match ours (check_auth( ) takes care of it), we render index.html, else we show a 401 response (see authenticate( )).

This tutorial covers the bare essentials of Flask. To learn more, go to Discover Flask that contains video tutorials covering pretty much everything in Flask. Also follow this thread for more Flask resources.

Feel free to leave a comment.