flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为:
default_config = ImmutableDict({ 'DEBUG': get_debug_flag(default=False), 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'USE_X_SENDFILE': False, 'LOGGER_NAME': None, 'LOGGER_HANDLER_POLICY': 'always', 'SERVER_NAME': None, 'APPLICATION_ROOT': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), 'TRAP_BAD_REQUEST_ERRORS': False, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': True, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, })
配置文件的实现方式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
app.secret_key = ['uaresocool'] app.debug = True # PS: 由于Config对象本质上是字典,所以还可以使用app.config.update(...) app.config.update(DEBUG=True) app.config['SECRET_KEY'] = 'uaresocool'
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# app.py app.config.from.pyfile('settings.py') # settings.py SECRET_KEY = 'uaresobeautiful'
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# app.py import os os.environ['xxx'] = 'settings.py' app.config.from_envvar('xxx') # settings.py SECRET_KEY = 'uaremyangel'
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# app.py app.config.from_json('settings.py') # settings.py # 这里必须是json格式,因为内部会执行json.loads {"SECRET_KEY":"uaresb" } 方式四:基于json
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
app.config.from_mapping({'SECRET_KEY':'whatareu'})
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# app.py # 使用时只需要修改配置类 import settings app.config.from_object(settings.BaseConfig) # settings.py class BaseConfig(object): # 基础配置 NNN = 1 AAA = 0 class TestConfig(BaseConfig): # 测试环境配置 AAA = 111 class DevConfig(BaseConfig): # 开发环境配置 AAA = 222 class ProConfig(BaseConfig): # 线上环境配置 AAA = 333