如何在调试模式下阻止Flask初始化两次?

Mat*_*ock 83 python flask

在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)

  • 如何仍然使用重新加载器,但某些东西只初始化一次? (4认同)
  • 这个答案意味着没有解决方案,只有一个解决方法?禁用重新加载器通常不是可接受的权衡. (3认同)
  • `use_reloader = False`对我来说非常合适. (2认同)
  • 我发现了一个极端的情况,似乎使用“FLASK_ENV=development”并没有*将“add.debug”设置为true。最后我使用`if not (app.debug or os.environ.get("FLASK_ENV") == "development") or os.environ.get("WERKZEUG_RUN_MAIN") == "true":`。祝你好运,6个月内就能出结果…… (2认同)

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)

  • Downvote.当app重新加载时,在之后的第一个请求之后将再次调用`before_first_request`. (10认同)
  • 谢谢亚历克斯,但如果我正在做缓存加温或预先填充像"分类器"之类的东西,这将在第一次请求之前调用,使第一个请求变慢或在烧瓶服务启动时. (5认同)