Home >Backend Development >Python Tutorial >Why Does My Flask Dev Server Seem to Run Twice?
Why the Flask Dev Server Appears to Run Twice
In Flask, the Werkzeug library provides the development server with app.run(). Werkzeug utilizes a reloader to restart the process each time the code is updated. This reloader spawns a child process, causing the script to run again using subprocess.call().
When you run the dev server, the script is executed both by the original process and the child process, leading to the duplicate print lines.
Disabling the Reloader
To eliminate the extra execution, you can disable the reloader by setting use_reloader to False in app.run(). This will prevent the automatic reloading but also disable the live-reloading functionality.
Alternatively, you can use the flask run command with the --no-reload option.
Detecting the Child Process
If you need to distinguish between the original process and the child process, you can use the werkzeug.serving.is_running_from_reloader function, which returns True if you are in the child process.
Setting Module Globals
For setting up module globals across the lifespan of the web server, consider using the @app.before_first_request decorator. This decorator applies to a function that will be executed only once, after each reload, when the first request is received.
Considerations for WSGI Servers
If you deploy your application on a WSGI server that uses forking or new subprocesses, the before_first_request handlers may be invoked multiple times, once for each new process.
The above is the detailed content of Why Does My Flask Dev Server Seem to Run Twice?. For more information, please follow other related articles on the PHP Chinese website!