Home >Backend Development >Python Tutorial >Why Does My Flask Dev Server Show a Double Restart Message?

Why Does My Flask Dev Server Show a Double Restart Message?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 15:44:11683browse

Why Does My Flask Dev Server Show a Double Restart Message?

Double Restart Printout in Flask Dev Server

When running a website development server using Flask, users have noticed an anomalous behavior where the server's restart message appears twice instead of once. To understand the reason behind this, let's delve into the mechanics of Flask's development server.

Flask utilizes Werkzeug, a WSGI utility library, to launch the development server through the app.run() method. Werkzeug employs a technique called "reloading" to automatically restart the server upon detecting changes in the code. The reloading process involves spawning a child process that runs your Flask script again using subprocess.call().

This child process assumes the same code as the parent process, leading to the double execution of the restart message. To eliminate this behavior, set the use_reloader parameter of app.run() to False. Alternatively, disable the reloader during the command-line execution of Flask:

FLASK_DEBUG=1 flask run --no-reload

For advanced scenarios where detecting the presence of the reloading child process is crucial, utilize Werkzeug's is_running_from_reloader() function. However, it's advisable to utilize the @app.before_first_request decorator for initializing module globals, guaranteeing a single execution after each reload.

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

Note that before_first_request handlers might be invoked for each new subprocess in full-scale WSGI servers that employ forking or new subprocesses.

The above is the detailed content of Why Does My Flask Dev Server Show a Double Restart Message?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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