Why Flask Dev Server Runs Twice During Development
When running the Flask dev server, users may notice the starting print line being displayed twice. This behavior stems from the use of Werkzeug's reloader, which creates a child process to facilitate updates when code changes.
Initiation of the Reloader
The Flask app is run with the app.run() method, which internally utilizes Werkzeug's development server. The restart_with_reloader() function launches a child process, causing the script to be rerun with subprocess.call().
Disable Auto-Reloading
To suppress the double print, set use_reloader to False in app.run(). Alternatively, use the flask run command with the --no-reload flag:
FLASK_DEBUG=1 flask run --no-reload
Detection of Reloading
To ascertain if the app is running in the reloading child process, employ the werkzeug.serving.is_running_from_reloader function.
Alternative for Module Globals
If module globals need to be set up, use the @app.before_first_request decorator to create a function that will be executed only once after each reload, upon the first request. However, note that this approach may lead to multiple invocations in WSGI servers utilizing multiple processes.
The above is the detailed content of Why Does My Flask Dev Server Appear to Start Twice?. For more information, please follow other related articles on the PHP Chinese website!