How to stop Flask from initialising twice in Debug Mode?

PythonFlask

Python Problem Overview


When building a Flask service in Python and setting the debug mode on, the Flask service will initialise twice. When the initialisation loads caches and the like, this can take a while. Having to do this twice is annoying when in development (debug) mode. When debug is off, the Flask service only initialises once.

How to stop Flask from initialising twice in Debug Mode?

Python Solutions


Solution 1 - Python

The simplest thing to do here would be to add use_reloader=False to your call to app.run - that is: app.run(debug=True, use_reloader=False)

Alternatively, you can check for the value of WERKZEUG_RUN_MAIN in the environment:

if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
    # The reloader has already run - do what you want to do here

However, the condition is a bit more convoluted when you want the behavior to happen any time except in the loading process:

if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true":
    # The app is not in debug mode or we are in the reloaded process

Solution 2 - Python

You can use the before_first_request hook:

@app.before_first_request
def initialize():
    print "Called only once, when the first request comes in"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt AlcockView Question on Stackoverflow
Solution 1 - PythonSean VieiraView Answer on Stackoverflow
Solution 2 - PythonAlex MoregaView Answer on Stackoverflow