如何在配置对象中使用`FLASK_ENV`?

How to use `FLASK_ENV` inside configuration objects?

遵循 Flask 文档中 Development / Production 的示例。是不是不能用FLASK_ENV配置flask环境?

>>> class DevelopmentConfig(Config):
...     FLASK_ENV = "development"
...     DEBUG = True
... 
>>> class ProductionConfig(Config):
...     FLASK_ENV = "production"
...     DEBUG = False
... 
>>> def create_app(config="ProductionConfig"):
...     app = Flask(__name__)
...     app.config.from_object(f"{__name__}.{config}")
...     return app
... 
>>> app = create_app("DevelopmentConfig")  # I CREATE AN APP USING DevelopmentConfig
>>> app.run()
 * Serving Flask app '__main__' (lazy loading)
 * Environment: production  # WHY IS ENVIRONMENT SET TO PRODUCTION?
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

所以我发现,虽然在外部你应该使用 FLASK_ENV 在内部你应该只使用 ENV.

>>> class DevelopmentConfig(Config):
...     ENV = "development"  # USE ENV INSTEAD OF FLASK_ENV
...     DEBUG = True
... 
>>> class ProductionConfig(Config):
...     ENV = "production"  # USE ENV INSTEAD OF FLASK_ENV
...     DEBUG = False
... 
>>> def create_app(config=ProductionConfig):
...     app = Flask(__name__)
...     app.config.from_object(config)
...     return app
... 
>>> app = create_app(DevelopmentConfig)
>>> app.run()
 * Serving Flask app '__main__' (lazy loading)
 * Environment: development  # NOW IS SET CORRECLY
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

尽管您可以从 settings 设置 ENVDEBUG,但它可能无法按预期工作,因此不推荐这样做。

In order to set the environment and debug mode reliably, Flask uses environment variables.

供您参考,Environment and Debug Features