In this post, we will take a brief look at the tool Flask, a microframework for creating web applications.
Prerequisites
An intermediate knowledge of version 2 of the Python programming language is recommended, as well as experience using PyPI and a GNU/Linux distribution; in this case, the examples will focus on the Debian distribution. This last requirement, the operating system, is recommended, although it is also possible to follow the process on a Windows or MacOS system, but some examples, such as installing Flask, will differ. In these cases, we recommend consulting the Flask quickstart guide.
Installation
Python and pip
If you do not yet have either of these two components installed, you can install it by opening a terminal and running:
# apt-get install python3 python3-pipFlask
As you might expect, we will use PyPI to install this component by running the following statement:
$ pip install FlaskFlask will be installed with its dependencies, so the operation may take some time to complete.
Virtualenv
This step is optional but highly recommended, although only for development purposes, not production. Virtualenv is a virtual environment (as you might expect) for separating libraries installed globally on the system from those of a project, having different versions of the same package…
To do this, run:
# apt-get install python-virtualenv o # python3-venvCreate a virtual environment
To do this, create a folder to hold our Flask project, then run virtualenv:
$ mkdir MiProyectoFlask
$ cd MiProyectoFlask
$ virtualenv venvNext, activate virtualenv to access the virtual console as well and enjoy the benefits it offers (some of which were mentioned earlier):
$ . venv/bin/activateAs you can see in the terminal, a “(venv)” marker has been added to the input line, indicating that we are in that environment. Now install Flask as described earlier, but this time in the virtual environment rather than globally on the system.
Create an app
The next step is to create the source file that will hold our application's content. In the project's root folder, simply create a new `app.py` file using your favorite text editor, such as Vim.
For purely educational purposes, we will create the typical Hello World application to see how to create a Flask project. Add the following lines to the file you created:
from flask import Flask # Import the library
app = Flask(__name__)
@app.route('/') # Web app route, in this case the root of the web page
def hello_world():
return 'Hola Mundo'Next, run the application with:
$ flask runThe terminal will display a local web address, which we will access using a web browser. The message “Hola Mundo” will appear on the screen, on an empty web page.
To add more pages to our website, simply define a new function (as you normally would in Python) and enter the statement `@app.route(RUTA)` on the preceding line, where _RUTA_ refers to the website address.
Various concepts
Display HTML
You can add static web pages stored in HTML format. Simply save the HTML file in a child directory of the project root called _templates_ and add the following lines:
# from flask import render_template
# @app.route('/info/')
# def hello():
# return render_template('info.html')Here, info.html is the document to display. The function used can accept more parameters and even decide which part of the HTML to display based on those parameters, for example, in a document using Jinja2.
Extensions
Base Flask, that is, without extensions installed, has powerful but limited functionality. To address this, a number of extensions have been created to expand this program's capabilities, from REST support to forms or email.
The easiest way to install an extension is to use PyPI; for example, to add email support, you can install Flask-Mail, as follows:
$ pip install Flask-MailUsing Cloud VPS
Everything covered so far has been run on a local machine, without being available on the Internet. Naturally, when creating a web application, the intention is to publish it when it is ready, so we must follow a series of steps to publish it on our Cloud VPS. For deployment on a server, some knowledge of Apache is recommended in addition to the knowledge described earlier.
To do this, create a new VPS with a GNU/Linux distribution (Debian, for example). Processor and RAM requirements will depend on the processing our code needs, as well as the number of users connecting to our website at the same time. Python itself is a language that generally needs more resources than others such as C, so these resources must be carefully assessed. Disk requirements will depend on whether we have a database and on our application's own files; this storage is easier to measure.
Obviously, to run this app on the server, the same packages must be installed as on the local machine, so we assume they are installed. To deploy our application, we will use `mod_wsgi`, an Apache module. To install it:
# # apt-get install apache2 libapache2-mod-wsgi-py3 y reiniciamos el servidor Apache `# systemctl restart apache2And run it:
# a2enmod wsgiNext, create (or copy) our Flask application as explained earlier, with one exception: instead of creating the application's entry point in `app.py`, we will do so in `/var/www/MiProyectoFlask/MiProyectoFlask/__init__.py` (yes, there is a child directory with the same name as its parent; this is not an error). Activate our virtualenv as described earlier as well. Run it as follows:
# python __init__.pyWe should see a message like the one on our local computer, showing a local address (even though it is on the server, we are on the right track).
Deactivate virtualenv with:
# deactivateNow it is time to create the .wsgi file for our Apache server. To do this, navigate to `# cd /var/www/MiProyectoFlask` and create a file named `miproyectoflask.wsgi` with the following content:
#!/usr/bin/python
import sys
sys.path.insert(0,"/var/www/MiProyectoFlask/")
from MiProyectoFlask import app as applicationFinally, configure Apache. First, configure the virtual host: use your preferred text editor to open the file (which does not exist yet) `/etc/apache2/sites-available/MiProyectoFlask.conf`, and write the following lines in it:
<VirtualHost *>
ServerName example.com
WSGIScriptAlias / /var/www/MiProyectoFlask/miproyectoflask.wsgi
<Directory /var/www/MiProyectoFlask>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>And run it:
# a2ensite MiProyectoFlask
# service apache2 restartBefore viewing the result, configure our server's firewall as desired, allowing HTTP access, for example as follows:
Access
This allows access from any IP; this may not be desirable in a particular case, so configure it carefully.
And finally, we can see our application, in this case _Hello World_:
Troubleshooting
When running the command `# service apache2 restart`, the following error may appear on the screen:
Job for apache2.service failed because the control process exited with error code.See "systemctl status apache2.service" and "journalctl -xe" for details. To see the cause of this situation in more detail, it is useful to run: `# systemctl status apache2.service` to view the Apache log. We may get a message like the following:
prueba systemd[1]: Starting The Apache HTTP Server...
prueba apachectl[981]: AH00112: Warning: DocumentRoot [/var/www/html] does not exist.To fix this, simply delete the file /etc/apache2/sites-enabled/000-default.conf.
Documentation
This microframework offers countless additional features. Some of them can be found in the Flask documentation, along with a number of useful manuals.