Use the Flask development server

Flask

Today we’re going to talk about the development server and debugging system of Flask. They depend on the Werkzeug library. WSGI Comprehensive Web Application Library, a project that started as a simple collection of various utilities for WSGI applications and has grown into one of the most advanced libraries.

app.run()

The Flask module has its own server to test the application during development, this server is started by the run() method, this method can contain various argument options to be managed. Let’s review the previously written article on installing the system and take the sample code.

from flask import Flask

// Create the flask object
app = Flask(__name__)

// Create the views
@app.route("/")
def homePage():
    return "<h1>Hello World</h1>"

// Launch the application without the debug system‹›
if __name__ == '__main__':
    app.run()

Let’s now examine the last two lines which are precisely the ones we need to start the server and test the project. The line:

if __name__ == '__main__':

It is used to ensure that the development web server is only started when the script is run directly. And the line:

app.run()

Here the run() method will be called from the app object which will start the server in a cycle which will wait for requests, and will serve answers, until it is interrupted by the user, for example with a CTRL-C.
To launch the application then just type the command from the terminal

python nomeFile.py

Open a browser and type in the address bar:

localhost:5000

Or:

127.0.0.1:5000

As mentioned earlier the run() method supports several different options which we will see below.

  • host – the hostname to listen on.
  • port – the port of the web server.
  • debug – if provided, enable or disable debug mode.
  • load_dotenv – load the closest .env and .flaskenv files to set the environment variables.
  • use_reloader – the server should automatically restart the python process if the modules have changed.
  • use_debugger – debug werkzeug should be used.
  • use_evalex – the exception evaluation function should be enabled.
  • extra_files – a list of files the reloader should watch in addition to modules.
  • reloader_interval – the reloader interval in seconds.
  • reloader_type – the type of charger to use.
  • threaded – the process should handle each request in a separate thread.
  • processes – if greater than 1, handle each request in a new process up to this maximum number of concurrent processes.
  • passthrough_errors – set this to True to disable error trapping.
  • ssl_context – an SSL context for the connection.

During development it is convenient to enable debug mode, which among other things activates the debugger and reloader. This is done by passing the debug argument set to True.

if __name__ == '__main__':
    app.run(debug=True)

flask run

The Flask system provides another way to start the development server by using a command line interface module via the flask command, which is installed directly with the Flask instance. To activate the server, just open a terminal, go inside the project folder and run the command:

flask run

Before launching this line, it is necessary to tell the flask command where the Flask application instance is located, so that it can import and use it. This is done by setting an environment variable as follows:

Per Mac e Linux
export FLASK_APP=nomeFile.py
Per Windows
set FLASK_APP=nomeFile.py

By opening a browser at the address 127.0.0.1:5000 we will see the application work.
Very important to improve the development work conditions is to use the debugging system. This allows the application to update the changes made to the code in runtime, otherwise after each change you would have to exit the development server and re-enter it, instead you only need to refresh the page to see the applied changes. To do this, you need to set another environment variable:

Per Mac e Linux
export FLASK_ENV=developement
Per Windows
set FLASK_ENV=developement

In the last versions this mode is deprecated even if at the moment it is still working, and it has been replaced by another environment variable:

export FLASK_DEBUG=1

So every time we enter the virtual environment and start the development work we have to run these commands:

export FLASK_DEBUG=1
export FLASK_APP=nomeFile.py
flask -- debug run

Honestly, this system can be improved by making the setting of environment variables permanent in a file. We do this by installing python-dotenv, this package reads key-value pairs from an .env file and can set them as environment variables.

pip install python-dotenv

Once installed we create a file called .flaskenv and edit the environment variables mentioned above inside it.

FLASK_DEBUG=1
FLASK_APP=nomeFile.py

At this point it will no longer be necessary to recall them at the first start of the server, an operation which will be done directly by the system by reading the.env file.
If we don’t want to set environment variables or create .env files or not use the python-dotenv, simply run the command:

flask --app=nomeFile.py --debug run

The wording listed above replaces the environment variables.
Using the flask run mode we could also delete lines of code from the program:

if __name__ == '__main__':
    app.run()

Since they are no longer necessary, even if they can still coexist without creating problems.

Conclusions

It’s not much of a difference whether you use one way or the other to run the development server, both are equally fine although the Flask project team recommends using the flask run option. However, the choice remains at the discretion of the developer depending on their context. The only thing that can be said against app.run() is that there may be problems reloading the page after a change. Obviously these ways are good only in the development phase and not in the face of production. For a production deployment, use a production-ready web server such as gunicorn or uWSGI.

Extra

If we wanted to see the application run on other devices in addition to the local one, we need to connect them to the same network and launch the command:

flask run --host="IP address of the machine where the server is launched"

Example in my case:

flask run --host=192.168.1.115

By taking a device and writing 192.168.1.115:5000 in the address bar, you can test the app directly.

 

SviluppoMania
Stay Tuned

MARCO.VERGNANI

Nella mia vita a 12 anni e' entrato a far parte un Intel 80286 con 4MB di RAM, un Hard disk da 20 MB e una primissima scheda VGA appena uscita e da allora mi si e' aperto un mondo pieno di bit. Appassionato di programmazione fin da piccolo, mi diverto a costruire piccoli robottini. Curioso delle molteplici applicazioni che le macchine automatiche possono compiere, e adoro vedere volare quegli strani oggetti chiamati droni.

Related Posts

This site uses Akismet to reduce spam. Learn how your comment data is processed.