Introducing Flask

Flask is a micro framework designed to facilitate the development of web applications under the MVC pattern and provides a simple interface. The main advantage is that it doesn't require any complex preconfiguration; all we need to do is install it with a command:

>>> pip install flask
Downloading/unpacking flask

Flask can also be downloaded from the project's home page at http://flask.pocoo.org. Note that to run Flask under Python 3, you will need Python 3.3 or higher.

Among the main features of Flask, we can highlight the following:

Among the main objects and methods that Flask provides for work, we can highlight the following:

Our app is going to allow us to browse the docstrings for the Python built-in functions. An application that's built with Flask is basically an instance of the Flask object, which we will record routes in.

You can find the following code in the flaskapp_demo.py file on the GitHub repository (https://github.com/PacktPublishing/Learning-Python-Networking-Second-Edition):

#!/usr/local/bin/python3

from flask import Flask, abort

app = Flask(__name__)
app.debug = True
objs = __builtins__.__dict__.items()

docstrings = {name.lower(): obj.__doc__ for name, obj in objs if
name[0].islower() and hasattr(obj, '__name__')}

...

Flask includes a development web server, so to try it out on our application, all we need to do is run the following command:

$ python flaskapp_demo.py

* Serving Flask app "demo" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 190-598-045
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

We can see that the Flask server tells us the IP address and port it's listening on. Connect to the http://127.0.0.1:5000/ URL. It will now display in a web browser, and you should see a page with a list of Python built-in functions. Clicking on one should display a page showing the function name and its docstring. If you want to run the server on another interface or port, you can change this data in the app.run() call, for example, to app.run(host='0.0.0.0', port=5000).

Let's go through our code. From the top, we created our Flask app by creating a Flask instance, in this case giving it the name of our main module. We then set the debug mode to active, which provides nice tracebacks in the browser when something goes wrong, and also sets the development server to automatically reload code changes without needing a restart. Note that the debug mode should never be left active in a production app! This is because the debugger has an interactive element, which allows code to be executed on the server. By default, debug is off, so all we need to do is delete the app.config.debug line when we put the app into production.