Flask 忽略配置 Class

Flask ignores config Class

我正在尝试使用 classes 设置配置文件,出于某种原因,Flask 忽略了配置 class.

上的设置

config.py:

class Config:
    FLASK_ENV = 'development'

__init__.py:

from flask import Flask

def init_app():
    # Set up core app
    app = Flask(__name__)
    app.config.from_object('config.Config')

    with app.app_context():
        # Import app routes
        from .index import routes

        # Register blueprints
        app.register_blueprint(routes.index_bp)

    return app

文件结构为:

.
├── config.py
├── requirements.txt
├── application
│   ├── __init__.py
│   └── index
│       ├── routes.py
│       ├── static
│       └── templates
└── wsgi.py

当我使用环境变量来设置 flask 环境时,它工作得很好,但是,我看过一些教程,比如 this one,它们使用 classes 来定义使用 Python 文件进行配置。

更新: 我在配置字典中添加了一个打印语句,因为我想检查配置是否正在加载,确实,它已加载:

 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
**development**
 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

我也尝试使用 app.config['FLASK_ENV']='development' 指定设置,但它仍然忽略它。看来 Flask 直接忽略了我的配置设置,这是我的入口点文件,以防万一:

from application import init_app


app = init_app()

if __name__ == "__main__":
    app.run()

引自 Flask 配置处理文档:

While it is possible to set ENV and DEBUG in your config or code, this is strongly discouraged. They can’t be read early by the flask command, and some systems or extensions may have already configured themselves based on a previous value.

https://flask.palletsprojects.com/en/1.1.x/config/

如您所见,应用程序在启动时需要变量,否则您的系统可能配置不正确。

您可以尝试取消设置之前的环境变量,这可能会奏效。