Home > Backend Development > Python Tutorial > Why Does My Flask Development Server Appear to Execute Twice?

Why Does My Flask Development Server Appear to Execute Twice?

DDD
Release: 2024-12-09 17:41:19
Original
484 people have browsed it

Why Does My Flask Development Server Appear to Execute Twice?

Flask Development Server Executing Twice: Unveiling the Reason

The Flask development server handles the restarting of your application whenever changes are made to your code. This functionality is provided by the Werkzeug library's restart_with_reloader() function.

This function spawns a child process, executing your script again using subprocess.call(). Consequently, both the original script and the child process print the restart message once each, resulting in the observed double print behavior.

Disable the Reloader

To eliminate this behavior, disable the reloader by setting use_reloader to False:

app.run(port=4004, debug=config.DEBUG, host='0.0.0.0', use_reloader=False)
Copy after login

Alternatively, you can use the flask run command with the --no-reload flag:

FLASK_DEBUG=1 flask run --no-reload
Copy after login

Detect the Reloader Process

Use the werkzeug.serving.is_running_from_reloader() function to detect the child process:

from werkzeug.serving import is_running_from_reloader

if is_running_from_reloader():
    print(f"################### Restarting @ {datetime.utcnow()} ###################")
Copy after login

Use @app.before_first_request Decorator

If you need to set module globals, consider using the @app.before_first_request decorator:

@app.before_first_request
def before_first_request():
    print(f"########### Restarted, first request @ {datetime.utcnow()} ############")
Copy after login

This decorator executes the function once after every reload, when the first request is made.

Note:

In full-scale WSGI servers using forking or subprocesses to handle requests, before_first_request handlers may be invoked for each subprocess.

The above is the detailed content of Why Does My Flask Development Server Appear to Execute Twice?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template