如何停止Flask在debugging模式下初始化两次?

在Python中构buildFlask服务并设置debugging模式时,Flask服务将初始化两次。 当初始化加载caching等时,这可能需要一段时间。 在开发(debugging)模式下,必须这样做两次会很烦人。 debuggingclosures时,Flask服务只会初始化一次。

如何停止Flask在debugging模式下初始化两次?

这里最简单的做法是将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 

但是,如果您希望加载过程之外的任何时候发生这种情况,则情况会更加复杂:

 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 

你可以使用before_first_request钩子:

 @app.before_first_request def initialize(): print "Called only once, when the first request comes in"