Flask is a microframework written in Python. It is a lightweight Web application framework, which uses the Werkzeug WSGI and Jinja2 template engine. There is no database abstraction layer or form validation layer, because the core is kept simple and supports extensions, which can add application features. There are many different extensions available for Flask to support databases, upload files, for authentications, form validation, etc, which the user has to import and use.
The Werkzeug WSGI (Web Server Gateway Interface)
WSGI is the interface between Web servers and Web applications for Python. At present, Werkzeug is one of the most advanced WSGI utility modules. It includes a powerful debugger, fully featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads and a powerful URL routing system. It does not force you to use a specific template engine or any other extension, but leaves everything else to you, the developer, to choose.
Jinja2
This template engine is mainly used for creating static or dynamic Web pages with minimal coding. A basic layout can be set up and used for a large number of static or dynamic pages with little coding. Flask uses the Jinja2 template engine, inspired by the Django framework. The Jinja template adds sandboxed execution for security reasons. It features the automatic escape of HTML from XSS Vulnerability and uses inheritances.
Flask is built on the above two libraries, the Jinja2 template engine and Werkzeug WSGI. The remaining decisions are left to you, as the developer. You can choose different extensions depending on your needs and interests. Lets create a simple Web application using Flask.
Flask installation
As a prerequisite, you need Python 2.6 or higher to get started, and Pip, which is a tool to install and manage Python packages. Pip makes it easy for users to install and uninstall Python packages in a single command. For example:
$pip install PackageName $pip uninstall PackageName
You have two ways to install Flask on your machine. You can either choose a virtual environment that allows you to work in an isolated environment with a separate copy of Python, and without worrying about affecting other projects if anything goes wrong, or you can go for a direct installation of Python and Flask on your native machine. I have explained both the methods here.
Let us first try the virtual environment using Pip. Ubuntu users can try it directly without Pip.
$sudo pip install virtualenv
Ubuntu users should use:
$sudo apt-get install python-virtualenv
to begin the virtual environment, and activate it by issuing the following command:
$ virtualenv venv $ . venv/bin/activate
You can deactivate virtualenv as follows:
$deactivate
Once you have activated virtualenv, you are ready to install Flask in the virtual environment. Do so by using Python package management.
$pip install Flask $pip install flask-script
You can install Flask directly in the system by avoiding the virtual environment (sometimes Flask comes with Python):
$ pip install Flask $ pip install flask-script
Once successfully installed, you can go ahead to create a simple Web application.
Our first app
Lets create a directory for our application to start off with Flask, as follows:
$ mkdir myapp $ cd myapp File structure: myapp __init__.py manage.py templates/ about.html base.html index.html posts.html static/ css/ style.css
Create the directories and files which are listed above.
__init__.py will create an object for application using Flask and will be ready to run the app.
manage.py will handle all URL routing properties and content. The templates directory contains all HTML pages needed for the applications and static contains all static resources like the style sheet, images, etc; this is handled by the Jinja2 template engine.
__init__.py file
from flask import Flask app = Flask(__name__) if __name__ == __main__: app.run(debug = True)
The above code will create an instance (app) for our app using the Flask class. The app.run method is used to run the local server with our application; we have imported the app object via manage.py, so we can run the server from there.
debug = True will automatically restart and reload the server if any modifications are done to any file of the application.
The app.run method is not actually needed here, because we are going to import app instance in the manage.py file and we can run the server from the manage file.
manage.py file from flask import Flask, url_for, render_template from flask.ext.script import Manager, Server import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),..))) #importing app from the __init__.py file, path can be obtained from the above statement from article import app manager = Manager(app) # main page can load either url 127.0.0.0:5000/ or 127.0.0.0:5000/index @app.route(/) @app.route(/index) def index(): return render_template(index.html, title = Myapp home) #About page @app.route(/about) def about(): return render_template(about.html, title= About) # load posts page and displays the content from the post array @app.route(/posts) def posts(): posts = [ { title : Hello World, body : Welcome to python flask tutorial }, { title : Sample post, body : Sample post for testing python flask } ] return render_template(posts.html, title = Posts, posts = posts) # Create a new command runserver using Manager and set host and enable debugger module. # Debugger module only for developing not for production server manager.add_command(runserver, Server( use_debugger = True, use_reloader = True, host = 127.0.0.1 )) #manager.run will start the server, which holds the app object also from the file __init__.py registered using Manager if __name__ == __main__: manager.run()
Import all necessary modules for our app. The render_template module in Flask uses the Jinja2 template, which automatically locates the file from the templates directory in the app. You can pass the template name and arguments as well. url for is good for building URLs. Instead of hard code, the URLs passing the function names will take care of everything and arguments will also be accepted.
The application path can be obtained from modules os and sys, and app object is imported from the __init__.py file.
manage.py will take care of routing and content in our application. Routing can be done using the @app.route() method, which takes string arguments and will be appended to the URL, e.g., @app.route(/index). You can load the index page with the help of http://127.0.0.0:5000/index.
render_template will, by default, look for HTML pages in the template directory, which takes the first argument as a page name and passing key; value pairs are also possible in the render_template method and values can be received using its key.
Manager module in Flask-script allows the user to create a new command. Using the add_command we can set up the server and new command. Here, we used runserver as our new command, and server settings like debugging, reloading and application IP address. Enabling debugger (use_debugger = True) is recommended for the purpose of testing and not for the production environment. It will display an error message if something goes wrong, and reloader (use_reloader = True) will automatically reload the applications after we have made changes to the code.
You can run the application using ./manage.py runserver. runserver is our own command, which has been created using the Manager module.
base.html
<!DOCTYPE html> <html> <head> {% if title %} <title> {{title}}</title> {% else %} <title> Myapp home</title> {% endif %} <link rel=stylesheet type=text/css href={{ url_for(static, filename=css/style.css) }}> </head> <body> <header> <h1><a href={{url_for(index)}}>MyApp</a></h1> </header> <div class=menu> <ul> <li><a href={{url_for(index)}}>Home</a></li> <li><a href={{url_for(about)}}>About</a></li> <li><a href={{url_for(posts)}}>Post</a></li> </ul> </div> <div class=container> {% block content %}{% endblock %} </div> </body> </html>
Jinja2 supports control and loop structures in the template by using flowerbraces {{ }}. base.html is the basic layout for our Web application. Other pages can simply extend this page and the rest of the operations will be handled by Jinja2.
index.html
{% extends base.html %} {% block content %} <h1>Welcome to my app</h1> {% endblock %}
The Jinja2 template allows inheritance, and the index file inherits the basic layout from base.html.
about.html
{% extends base.html %} {% block content %} <p>This is about page of flask</p> {% endblock %}
posts.html
{% extends base.html %} {% block content %} {% for post in posts %} <div class=title> <h2>{{post.title}} </h2> </div> <div class=content> <p>{{post.body}}</p> </div> {% endfor %} {% endblock %}
In manage.py, the content for the post page is passed using the render_template method and can be identified using its key.
style.css
a { text-decoration: none; } header { padding : 2px; margin-left: 50px; margin-top: 10px; width : 130px ; height: 70px; border-radius: 5px; background-color: #C2BABC; } ul li{ list-style: none; display: inline; float: right; padding: 10px; } ul li a{ background-color: #2E2E2E; color :#FFF; border-radius: 3px; } .container { margin-top: 20px; margin-left: 70px; width: 500px; } .title { background-color:#C2BABC; }
Creating Web applications using Flask is very simple and needs little or no experience, when compared to other languages. The server part will be handled by Flask, and no extra server setup is needed. Flask is known for its simplicity. The core API is simple and is based on the Jinja2 template engine and the Werkzeug WSGI toolkit. It allows developers to choose their own third party Python packages depending on their interests. Using Flask is a good option for complex Web applications. It makes the applications easy to understand and enables developers to work on different modules efficiently.
References
[1] http://en.wikipedia.org/wiki/Flask_(web_framework)
[2] http://werkzeug.pocoo.org/
[3] http://jinja.pocoo.org/
[4] http://flask.pocoo.org/
[5] http://flask.pocoo.org/docs/installation/#installation