How to stop Flask from initializing twice in debug mode?

When you create a Flask service in Python and set up debug mode, the Flask service will be initialized twice. When initialization loads caches and the like, this may take some time. This requires annoyance twice in development (debugging) mode. When debugging is disabled, the flag service only initializes once.

How to stop Flask from initializing twice in debug mode?

+44
python flask
Feb 25 2018-12-25T00:
source share
2 answers

The simplest task 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 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 complicated if you want the behavior to occur at any time other than the boot 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 
+68
Feb 28 2018-12-12T00:
source share
— -

You can use before_first_request hook:

 @app.before_first_request def initialize(): print "Called only once, when the first request comes in" 
+19
Feb 26 2018-12-12T00:
source share



All Articles