如何阻止 Flask 在调试模式下初始化两次? [英] How to stop Flask from initialising twice in Debug Mode?

查看:33
本文介绍了如何阻止 Flask 在调试模式下初始化两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中构建 Flask 服务并设置调试模式时,Flask 服务将初始化两次.当初始化加载缓存等时,这可能需要一段时间.在开发(调试)模式下,必须这样做两次很烦人.当调试关闭时,Flask 服务只初始化一次.

When building a Flask service in Python and setting the debug mode on, the Flask service will initialise twice. When the initialisation loads caches and the like, this can take a while. Having to do this twice is annoying when in development (debug) mode. When debug is off, the Flask service only initialises once.

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

How to stop Flask from initialising twice in Debug Mode?

推荐答案

这里最简单的做法是将 use_reloader=False 添加到您对 app.run - 即:app.run(debug=True, use_reloader=False)

The simplest thing to do here would be to add use_reloader=False to your call to app.run - that is: app.run(debug=True, use_reloader=False)

或者,您可以检查

Alternatively, you can check for the value of WERKZEUG_RUN_MAIN in the environment:

if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
    # The reloader has already run - do what you want to do here

但是,如果您希望行为在加载过程中之外的任何时间发生,则条件有点复杂:

However, the condition is a bit more convoluted when you want the behavior to happen any time except in the loading process:

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

这篇关于如何阻止 Flask 在调试模式下初始化两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆