在Python中构建Flask服务并设置调试模式时,Flask服务将初始化两次.当初始化加载高速缓存等时,这可能需要一段时间.在开发(调试)模式下,必须执行此操作两次都很烦人.关闭调试时,Flask服务仅初始化一次.
如何在调试模式下阻止Flask初始化两次?
Sea*_*ira 117
这里最简单的方法是添加use_reloader=False你的电话app.run- 即:app.run(debug=True, use_reloader=False)
或者,您可以检查WERKZEUG_RUN_MAIN环境中的值:
if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
# The reloader has already run - do what you want to do here
Run Code Online (Sandbox Code Playgroud)
但是,当您希望除了加载过程之外的任何时间都要发生这种情况时,条件会更复杂:
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
Run Code Online (Sandbox Code Playgroud)
Ale*_*ega 16
你可以使用before_first_request钩子:
@app.before_first_request
def initialize():
print "Called only once, when the first request comes in"
Run Code Online (Sandbox Code Playgroud)