Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Flask from initialising twice in Debug Mode? [duplicate]

Tags:

python

flask

People also ask

Why does running the Flask dev server run itself twice?

Answer #1: The Werkzeug reloader spawns a child process so that it can restart that process each time your code changes. Werkzeug is the library that supplies Flask with the development server when you call app.

How do I set my Flask debug true?

To enable the debugger, run the development server with the FLASK_ENV environment variable set to development . This puts Flask in debug mode, which changes how it handles some errors, and enables the debugger and reloader. FLASK_ENV can only be set as an environment variable.

What does Flask debug mode do?

Flask Debug mode allows developers to locate any possible error and as well the location of the error, by logging a traceback of the error. The Flask debug mode also enables developers to interactively run arbitrary python codes, so that one can resolve and get to the root cause on why an error happened.


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

You can use the before_first_request hook:

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