我在 Flask 中加载配置时遇到了麻烦。
from config import config, DevelopmentConfig, TestingConfig, ProductionConfig
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name]) # Doesnot load configuration
app.config.from_object(DevelopmentConfig) # Loads configuration succesfully.
我已经检查了 config[config_name] 等的类型。它们很好。
配置文件如下所示。导入对象类型没有问题。如果静态通过,一切正常。'host'='serverip' 是故意的。
此外,当我尝试使用 SQLAlchemy 连接到 db 时不会出现此问题,但对于 MongoDB,它不会更新应用程序设置中的 MONGODB_SETTINGS。
import os
basedir = os.path.abspath(os.path.dirname(__file__))
from helper.helper_functions import generate_secret_key
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or generate_secret_key()
SSL_DISABLE = False
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
MONGODB_SETTINGS = {
'DB': 'development_db',
'host': 'localhost',
'port': 27017
}
class TestingConfig(Config):
TESTING = True
WTF_CSRF_ENABLED = False
MONGODB_SETTINGS = {
'DB': 'testing_db',
'HOST': 'localhost',
'PORT': 27017
}
class ProductionConfig(Config):
MONGODB_SETTINGS = {
'DB': 'production_db',
'host': 'server_ip',
'port': 27017, # default =27017
# other settings...
}
@classmethod
def init_app(app):
Config.init_app(app)
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': TestingConfig,
}
有趣的是。
app.config.update(MONGODB_SETTINGS={'DB':'testing_db'}) # works
settings = dict([('db', 'testing_db')])
app.config.update(MONGODB_SETTINGS=settings) # Does not work
此外,当我尝试使用 Flask-Config 提供的其他方法从配置文件加载配置时。
conf_name = 'test-config.py'
app.config.pyfile(conf_name) # Doesnot load the configuration from the file.
app.config.pyfile(''+conf_name) # Doesnot load the configuration from the file.
app.config.pyfile('test-config.py') #successfully loads the configuration from file.