Auto reloading python Flask app upon code changes
The current recommended way is with the flask
command line utility.
https://flask.palletsprojects.com/en/1.1.x/quickstart/#debug-mode
Example:
$ export FLASK_APP=main.py$ export FLASK_ENV=development$ flask run
or in one command:
$ FLASK_APP=main.py FLASK_ENV=development flask run
If you want different port than the default (5000
) add --port
option.
Example:
$ FLASK_APP=main.py FLASK_ENV=development flask run --port 8080
More options are available with:
$ flask run --help
FLASK_APP
can also be set to module:app
or module:create_app
instead of module.py
. See https://flask.palletsprojects.com/en/1.1.x/cli/#application-discovery for a full explanation.
If you are talking about test/dev environments, then just use the debug option. It will auto-reload the flask app when a code change happens.
app.run(debug=True)
Or, from the shell:
$ export FLASK_DEBUG=1$ flask run
In test/development environments
The werkzeug debugger already has an 'auto reload' function available that can be enabled by doing one of the following:
app.run(debug=True)
or
app.debug = True
You can also use a separate configuration file to manage all your setup if you need be. For example I use 'settings.py' with a 'DEBUG = True' option. Importing this file is easy too;
app.config.from_object('application.settings')
However this is not suitable for a production environment.
Production environment
Personally I chose Nginx + uWSGI over Apache + mod_wsgi for a few performance reasons but also the configuration options. The touch-reload option allows you to specify a file/folder that will cause the uWSGI application to reload your newly deployed flask app.
For example, your update script pulls your newest changes down and touches 'reload_me.txt' file. Your uWSGI ini script (which is kept up by Supervisord - obviously) has this line in it somewhere:
touch-reload = '/opt/virtual_environments/application/reload_me.txt'
I hope this helps!