为什么要导入配置文件呢? 我刚开始学习Flask的时候,觉得没这必要,所以直接忽略了
后来,app的配置越来越多,并且不同的py文件里的配置有重复,所以需要另外写一个配置文件,方便管理
## 官方文档上说的有3种方法
app.config.from_pyfile('yourconfig.cfg') # 1
app.config.from_object('yourapplication.defaultsettings') #2
app.config.from_envvar('YOURAPPLICATION_SETTINGS') # 3
一, yourconfig.cfg 默认是在当前文件的路径下,你可以使用绝对路径或是相对路径,对于文件是怎么写的,就是KEY = value 的键值对的形式的配置文件
</pre><pre name="code" class="python">
</pre><pre name="code" class="python">
二,如果'yourapplication.defaultsettings' 这个参数是字符串,则使用和方法1一样,如果是一个py对象文件,文件的写法内容就是一个class,
例如:
class Config(object):
DEBUG = True
MONGOSETTINGS = {'DB': 'test'}
然后先用import XXX引入文件,最后参数就是XXX.Config
三,这个方法就是给系统一个环境变量的配置文件路径,然后参数就是那个环境变量的值,linux系统用 export XXX=/../../.....设置环境变量
注意:
1,In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config.
就是说keys要大写
2, It is also possible to tell it to use the same module and with that provide the configuration values just before the call:
DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)
看例子顺序