设为首页 加入收藏

TOP

源码解析Flask的配置文件(二)
2018-04-13 06:06:30 】 浏览:554
Tags:源码 解析 Flask 配置 文件
件中定义(通常使用的方式)
app.debug = True
app.secret_key = 'helloworld!!'



由于Config对象继承了dict的方法和属性,所以还可以使用app.config.update(配置项)的方式导入配置项


2.从环境变量中导入配置项


导入配置项的方式:
app.config.from_envvar("环境变量名称")


from_envvar方法的源码:
def from_envvar(self, variable_name, silent=False):
   
    rv = os.environ.get(variable_name)
    if not rv:
        if silent:
            return False
        raise RuntimeError('The environment variable %r is not set '
                          'and as such configuration could not be '
                          'loaded.  Set this variable and make it '
                          'point to a configuration file' %
                          variable_name)
    return self.from_pyfile(rv, silent=silent)


可以看到,从环境变量中导入配置项的方法,就是从环境变量中找到并读取对应的py文件名称,然后内部调用from_pyfile方法处理读取到的内容得到配置


3.从python文件中导入


python文件中获取配置项的方式:
app.config.from_pyfile("python文件名称")


例如,创建一个名为setting.py的文件


setting.py文件的内容为:
DEBUG=True


然后使用app.config.from_pyfile("setting.py")的方式导入配置项


from_pyfile方法的源码:
def from_pyfile(self, filename, silent=False):


    filename = os.path.join(self.root_path, filename)
    d = types.ModuleType('config')
    d.__file__ = filename
    try:
        with open(filename, mode='rb') as config_file:
            exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
    except IOError as e:
        if silent and e.errno in (errno.ENOENT, errno.EISDIR):
            return False
        e.strerror = 'Unable to load configuration file (%s)' % e.strerror
        raise
    self.from_object(d)
    return True


从py文件中导入配置项的过程中,读取参数中的python文件的内容,进行编译后exec方法执行,就得到所需要的配置项


需要注意的是:


python文件可以是绝对路径或者相对路径,如果是相对路径,则py文件必须放在root_path目录下,


4.从对象中导入配置项


from_object方法的源码:
def from_object(self, obj):


    if isinstance(obj, string_types):
        obj = import_string(obj)
    for key in dir(obj):
        if key.isupper():
            self[key] = getattr(obj, key)


从对象中导入配置项的过程中,首先判断所传入的对象名是否是字符串,然后调用import_string方法处理字符串形式的对象名


import_string方法的源码:
def import_string(import_name, silent=False):


    import_name = str(import_name).replace(':', '.')
    try:
        try:
            __import__(import_name)
        except ImportError:
            if '.' not in import_name:
                raise
        else:
            return sys.modules[import_name]


        module_name, obj_name = import_name.rsplit('.', 1)
        try:
            module = __import__(module_name, None, None, [obj_name

首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python 函数介绍 下一篇Android对手机口袋状态的检测,距..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目