How to stop Flask from initialising twice in Debug Mode?
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
Why does running the Flask dev server run itself twice?
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.run()
.
See the restart_with_reloader()
function code; your script is run again with subprocess.call()
.
If you set use_reloader
to False
you'll see the behaviour go away, but then you also lose the reloading functionality:
app.run(port=4004, debug=config.DEBUG, host='0.0.0.0', use_reloader=False)
You can disable the reloader when using the flask run
command too:
FLASK_DEBUG=1 flask run --no-reload
You can use the werkzeug.serving.is_running_from_reloader
function if you wanted to detect when you are in the reloading child process:
from werkzeug.serving import is_running_from_reloader
if is_running_from_reloader():
print(f"################### Restarting @ {datetime.utcnow()} ###################")
However, if you need to set up module globals, then you should instead use the @app.before_first_request
decorator on a function and have that function set up such globals. It'll be called just once after every reload when the first request comes in:
@app.before_first_request
def before_first_request():
print(f"########### Restarted, first request @ {datetime.utcnow()} ############")
Do take into account that if you run this in a full-scale WSGI server that uses forking or new subprocesses to handle requests, that before_first_request
handlers may be invoked for each new subprocess.
Python program seems to be running twice
it's due to the reloader of flask/werkzeug, which reloads automatically when you change the code.
so give debug=False if you don't want/need that, e.g. for "production".
How to stop Flask from initialising twice in Debug Mode?
flask web app project sudden behavior change - connecting to debugger twice
I would try running with debug=False
or use_reloader
to prevent flask from restarting after detecting a change in your files and see if anything changes.
More info about the reloaded here:
How to stop Flask from initialising twice in Debug Mode?
The slowness in the startup could be attributed to any long running tasks in your app initialization code.
You would need to include more code or profile the code yourself to troubleshoot that.
If you are reading or writing from/to a network location IO might be your bottleneck.
Lastly, I recently went through an effort of troubleshooting/optimizing a flask app startup time - maybe something there could be useful to you:
Slow Flask Development Server Initialization Profiling: `WaitForSingleObject`
Python program seems to be running twice
it's due to the reloader of flask/werkzeug, which reloads automatically when you change the code.
so give debug=False if you don't want/need that, e.g. for "production".
How to stop Flask from initialising twice in Debug Mode?
Webbrowser.Open open two tabs
Your code is running in debug mode. app.run(debug=True)
. The Flask service will initialize twice in the debug mode. When debug is off, the Flask service only initializes once.
change the last line of your code app.run(debug=True)
to app.run(debug=True, use_reloader=False)
Related Topics
Pandas Index Column Title or Name
Salt and Hash a Password in Python
How to Remove Anaconda from Windows Completely
How to Get the Correct Dimensions for a Pygame Rectangle Created from an Image
How to Write to a File, Using the Logging Python Module
In Python, How to Index a List with Another List
How to Fit a Sine Curve to My Data with Pylab and Numpy
How to Run Python Script Without Typing 'Python ...'
Adding a Legend to Pyplot in Matplotlib in the Simplest Manner Possible
Matplotlib Legend Markers Only Once
List of Dicts To/From Dict of Lists
How to Get System Timezone Setting and Pass It to Pytz.Timezone
How Can One Continuously Generate and Track Several Random Objects with a Time Delay in Pygame