Linux Format

Flask web framework

Mats Tage Axelsson takes you through the steps to understand and start using the Flask web framework for Python – and for profit!

-

Mats Tage Axelsson helps you understand the Flask web framework for Python.

The main focus of Python has always been to get you cracking on with your coding – the language was never made for web programmin­g. However, this has just made it more interestin­g to extend the language for the web, or to create an interface to web-based technologi­es. Some of these efforts lead to, among others, Flask, Bottle (no, really) and Django. This article covers Flask, a microframe­work. The reason it is called a micro-framework is that it aims to be minimal; others, like Django, aim to have many solutions and support a lot of features.

Mini-me

The minimalist thinking behind Flask makes it ideal for the early stages of learning. Getting a project off the ground will take you a few hours if you follow the right instructio­ns. When you need more functions, Flask supports extensions so that you can add forms, database functions and so on. These extensions range from really simple additions for indexing and internatio­nalisation, to many databases. You can also fairly easily add your own extensions – if you have some programmin­g experience, of course.

You also have a management interface available as an extension, if you want. While this is useful, you will only need to use it for bigger changes; you’ll probably start using it when the complexity of the site reaches a certain point.

Flask can easily be set up as a content management system: a simple website with a few pages and a blog which you can create in a few hours with only prior knowledge of Python and HTML. If you think that ‘micro’ means only for hobby projects, think again: heavy hitters such as Pinterest and Linkedin use it for their sites.

Before you start using Flask, you need a Python environmen­t. Almost anyone who programs in Python uses virtual environmen­ts, and you should do the same. To create one using Python3, run venv in your project directory:

$ python3 -m venv .flask

While still in your project directory, activate the environmen­t before you start developing. You will need to repeat this each time you return to your project.

$ source .flask/bin/activate

Now you are running Python and pip in your environmen­t, rather than on your entire system. You’ll notice that (flask) has been added to the beginning of your prompt. This is the name of the environmen­t, which in turn is a directory where all your Python dependenci­es are stored. This environmen­t has a very basic Python file in it and you’ll need to install Flask to begin with, using:

$ pip install flask

Getting started

The simplest code to achieve is a ‘Hello World’ web page. With Flask you need just six lines to create one:

from flask import Flask app = Flask(__name__) @app.route(‘/hello’) def home():

return ‘Hello World!’ if __name__ == (‘__main__’): app.run(host=’localhost’)

You run the code by starting the flask server.

$ export FLASK_APP=HELLO.PY

$ flask run

As you may imagine, it will be cumbersome to point to each new file of code you write, so we will make an

__init__.py file later to bind your project files together.

The web page has no style of any kind, all it does is send a string to your browser. This code does a few more things that you will use later on, though.

The first line imports the framework so you can use it. The second line creates an instance of a Flask class. You can use many features of the framework thanks to that line. Next, you define a route to the hello subpage and you return the string. Since app is an instance of Flask, you have many other features available here.

Note that with this code, the root of the website (localhost:5000/) will throw an error – you will create the root later. For a real website, you want to use HTML. You could add the HTML in the Python code but that would be inefficien­t – it’s much better to use templates.

Jinja2 is a template engine. When using Flask, the render_template function will help you get there. In the code, you create variables that you add to your return statement. Add the below code to your hello.py file. from flask import Flask, render_template @app.route(‘/’) def home(): return render_template(‘index.html’, name = name) In this code, you get the name variable from the URL in the top. The render_template call contains the name and your index.html file will use it.

home

nice to see you {{ name }}

As you can see, the variable is used in the {{ name }}

statement. You will call all variables from your Python code this way. You will also read data from databases, and put them in a variable in the same manner.

Hey, good looking

To make your web pages beautiful, you need CSS. Over the years, many people have created frameworks for the look of web pages, the most common being Bootstrap. This framework was developed by Twitter and is now almost a given for web pages that need to be responsive. With so many people using their phones to browse, this has become a necessity.

When you use Flask to create a website, you have a very basic design. However, as expected, there is a plugin: Flask-bootstrap. A base file defines what your site will look like; in this file, you add a link to use Bootstrap and define what it will look like. This is the same method that you will use to build everything when creating websites with Flask.

In the earlier code, your text looked a little better because it was in the Header 1 style, but to make it look really nice you need to add some CSS. You can add CSS in the main template, but the simplest way is to install Flask-bootstrap and add it to your project. Next, add it to your code: from flask_bootstrap import Bootstrap def create_app(): app = Flask(__name__)

Bootstrap(app)

Note that the app is now wrapped in a factory function. This way you can register new functions inside the factory and use them elsewhere. To make it look good you need to name the content you want according to Bootstrap.

The reason Flask is so powerful is that you have the base page defined for the whole project. This will keep everything in the project uniform and style will never change drasticall­y. You can usually upgrade the base page in very minor ways when you want to add new functions and features. There’s no real reason to change basic functions just to add emailing functions or make opt-in pages. To make a really good impression on your visitors, you need to make it comfortabl­e to use the whole site. If you start changing the logic and design of the site, visitors will start dropping off.

If you really want to do something revolution­ary, start a new project. With a micro-framework like Flask, you will be able to quickly create large, complex sites where visitors feel at home throughout the site.

Slippery serpent

Since Python was designed primarily for science and mathematic­s, using it for the web was not a priority – yet the most common use of the language is for web developmen­t. As always with Python, the right modules make it excellent for web programmin­g. It integrates very well with HTML and CSS, not to mention many database backends and Javascript frameworks.

Another common use is for scripting, as it’s easy to write simple functions. Modules which support more advanced mathematic­s and machine learning make these the third really large field where Python stands out. Thanks to Scipy, Numpy and Scikit-learn, the science is defined when using Python. You just need to add your special case with your code.

With Flask, you have a small set of functions from the start so you can tailor the package to your needs.

It’s also simple for an experience­d programmer to make a new extension to support their own needs. With the, erm, extensive use of extensions, you can start out with a very small footprint and grow as you need. Compare this to Django, where there are many more solutions available from the start.

Django (see page 82) for example, has an administra­tive interface in the main package; when you use Flask, you must add the relevant extension to get this functional­ity. So you need to decide if you want it all immediatel­y or start small and expend a bit more time initially building the first page.

Flask was designed as a wrapper to Werkzeug and Jinja2. Werkzeug supplies WSGI tools to make your programs easier to write and maintain. Werkzeug is German for ‘tool’, and this tool adds wrappers for everything HTML and HTTP. Because it is focused on web interactio­n, it also handles the request and response features of your websites.

What’s a Werkzeug?!

Thanks to Werkzeug, it’s easier to grab or create an HTTP header, parse it and use the request and response objects. You can also create and handle cookies, form data and more. It is thanks to Werkzeug that Flask has an in-browser debugger, which is based on Javascript but is part of the tool. There is also a test environmen­t, where you can easily create valid responses to test your code. Despite boasting all these features, Werkzeug has a small footprint.

With all these functions covered by Werkzeug and Jinja2, what does Flask actually do? Even its documentat­ion acknowledg­es that it’s a wrapper for these two frameworks. Its function is to bind everything together and add structure. Through Flask, you also have the debugger. You can enable the debugger with the environmen­t variable FLASK_ENV, set it to debug , then run Flask.

Once it’s active, you have debugging informatio­n available in your web browser. It also enables the autoreload­er, saving you the trouble of restarting the server each time you have made code updates. This is meant to be used only for your local developmen­t machine and not your production server. Be very clear about this, as the debugger opens up gigantic security holes that could lead to some nasty surprises.

Flask also provides a bridge of sorts between your applicatio­n and the Werkzeug client. With this in place you can hook up your favourite Python tester; the Flask documentat­ion uses pytest, so if you do not have a favourite already, use that.

Session handling

After having programmed in Python for a while, you get to know a few features that are common to larger projects. One of those features is packages, and to make a package you need to create a directory that contains a few special files. Flask has adopted the package approach for consistenc­y, so the /flaskr directory is created and used in the same manner as a package. Inside this directory are the files __init__.py, setup.py, LICENSE and README.MD – this also makes the directory ready to host on Github and similar sites. On that note, it’s a good idea to versioncon­trol your project, irrespecti­ve of its size.

The first file to consider is the __init__.py file, which contains the ‘factory’. What does that mean? Well, in its simplest form, any website you create is an instance of the Flask class defined globally. The instance is named ‘app’ by convention – you will see how this is used later on. Managing this when you make a web page quickly becomes clumsy. The common way to do it instead is to use a function inside where you place the instance.

This approach adds possibilit­ies to both connect pages and support the use of Jinja2 templates. When you create a website, you want to have many pages. The most common example is a blog where you want to have the posts on one page, an ‘About’ page and a few others. All the pages should look similar; usually, you want a bar at the top that helps the user recognise your site. The above is valid for all pages, since people want to recognise where they are after clicking a link.

Templates

In Flask and Jinja2, this is solved with templates. In your code, you have ‘blueprints’ that describe your base page. You usually create a page called base.html

or similar and then you use that file as a base. This feature is called extending a page, using the extends

statement in curly brackets and with per cent signs: from flask import Flask, render_template app = Flask(__name__) @app.route(‘/’) def index():

return render_template(‘index.html’) @app.errorhandl­er(404) def page_not_found(e):

return render_template(‘404.html’), 404 if __name__ == ‘__main__’:

app.run(debug=true)

{% extends ‘base.html’ %}

{% block header%}

{% block title%}about Me{% endblock %}

{% block content %}

404 Error :(

you have Gone the wrong way.

Turn back to the righteous path

{% endblock %}

This is the base for the template system. Code is denoted by curly brackets and the code calls to your Python code to generate the views – each view will be a page for the user. To create a view you start with

blueprints; this is a function made by the Flask team that acts as the template system.

Before you start using the blueprints functions, it is a good idea to understand how decorators work in Python. The basic idea is that one function can be wrapped in another – not quite like inheritanc­e, but pretty similar.

To present your page, you base it on the base.html

file. You then base other pages on that file: this is what {% extends ‘base.html’ %} does at the top of the code. Further, your later statements can create or replace the different blocks from the base.html file. These blocks are the known ones in HTML, namely header, title and body. You can also use conditiona­ls to control your page. These are in the form {% if %} and {% for ... %} .

The latter one is very useful for listing data from a database – for example, a blog. Blog posts will almost always be stored in a database and listing them will use a for loop.

Blueprints

In your Python code, you will have functions to build your page. To present it on the page you put the reference to the code in double curly brackets {{ . The connection here is the render_template function in the Python code.

You place styling in a separate file in the static/ directory by default. The main file base.html will point to the style.css file in that directory. You can opt to create more CSS files and call them from the child pages. However, that should be done only for separate styling of elements outside of the main bar. The power of this strategy is twofold. First, you have effectivel­y made your site look the same across all pages. Secondly, you can easily change the look of your entire site with just very small code changes to the main style.css file.

If you feel confused by the template system, look for tutorials and documentat­ion about Jinja2 – there are plenty available on the net. They will give you a solid foundation for creating great-looking websites. At the same time, Werkzeug tools can help you handle HTTP requests, creating the pages. It will also set up a service for debugging.

When you use the Flask framework, you can get dynamic content up quickly and with relative ease. Programmin­g in Python is a prerequisi­te but you only

need basic knowledge to get started. You will learn more advanced techniques as your project grows.

The same goes for your HTML knowledge: you do need it, but the basics will be enough since many more advanced features are taken care of by the framework. With all the extensions available for you to study, you can learn both HTML, CSS and Python while adapting them to your special case.

Flask has few features built-in which, at first glance, seems to limit its potential – but don’t jump to that conclusion immediatel­y. Instead, study the many extensions and see if you can build using those.

If you choose another framework, you will have more functions available from the start, but you will also be limited in what the final result looks like. The reason is that most other frameworks have all the basic concepts set from the beginning. You should choose carefully, since moving to another framework halfway through a project will be cumbersome though not impossible.

 ??  ?? Flask includes the internal debugger, and thanks to this you can see your Python code in the browser. Use this only while developing, as it opens security holes.
Flask includes the internal debugger, and thanks to this you can see your Python code in the browser. Use this only while developing, as it opens security holes.
 ??  ??
 ??  ?? When you want to start exploring Flask, make a very simple blog. The functions are the really basic ones, to create, update and delete blogs.
When you want to start exploring Flask, make a very simple blog. The functions are the really basic ones, to create, update and delete blogs.
 ??  ?? Emacs is great for testing your Flask applicatio­n. Here you can see the output of the server next to the init code of the Flask applicatio­n.
Emacs is great for testing your Flask applicatio­n. Here you can see the output of the server next to the init code of the Flask applicatio­n.
 ??  ?? Flask has a nice way to debug your code, but you can still add the flask-debugtoolb­ar to have debugging available as a sidebar while things are running.
Flask has a nice way to debug your code, but you can still add the flask-debugtoolb­ar to have debugging available as a sidebar while things are running.
 ??  ?? When you need to document and give yourself reminders about your code, create a Jupyter notebook and open it in Emacs. You can also open them in a terminal or in your browser.
When you need to document and give yourself reminders about your code, create a Jupyter notebook and open it in Emacs. You can also open them in a terminal or in your browser.

Newspapers in English

Newspapers from Australia