设为首页 加入收藏

TOP

源码解析Flask的配置文件(三)
2018-04-13 06:06:30 】 浏览:552
Tags:源码 解析 Flask 配置 文件
])
        except ImportError:
            module = import_string(module_name)


        try:
            return getattr(module, obj_name)
        except AttributeError as e:
            raise ImportError(e)


    except ImportError as e:
        if not silent:
            reraise(
                ImportStringError,
                ImportStringError(import_name, e),
                sys.exc_info()[2])


可以看到,import_string方法,实际上是对字符串形式的对象名执行rsplit方法,得到模块名和对象名


在模块可以被正常导入之前,不停执行import_string方法,最后执行getattr方法从模块中获取对象名


5.from_json:从json字符串中获取配置项


from_json方法的源码:
def from_json(self, filename, silent=False):
   
    filename = os.path.join(self.root_path, filename)


    try:
        with open(filename) as json_file:
            obj = json.loads(json_file.read())
    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
    return self.from_mapping(obj)



从json文件中获取配置项,实际上就是对json文件执行json.loads方法,得到对象


然后内部调用from_mapping方法处理所得到的对象


6.from_mapping:从dict字典中获取配置项


from_mapping方法的源码:
def from_mapping(self, *mapping, **kwargs):


    mappings = []
    if len(mapping) == 1:
        if hasattr(mapping[0], 'items'):
            mappings.append(mapping[0].items())
        else:
            mappings.append(mapping[0])
    elif len(mapping) > 1:
        raise TypeError(
            'expected at most 1 positional argument, got %d' % len(mapping)
        )
    mappings.append(kwargs.items())
    for mapping in mappings:
        for (key, value) in mapping:
            if key.isupper():
                self[key] = value
    return True


把参数字典中的所有键值对添加到列表串,循环遍历列表,读取列表中每???元素的键和值


如果键为大写,则key为配置选项,value为配置选项的值


7.get_namespace:从名称空间中获取配置选项


get_namespace源码:
def get_namespace(self, namespace, lowercase=True, trim_namespace=True):


    rv = {}
    for k, v in iteritems(self):
        if not k.startswith(namespace):
            continue
        if trim_namespace:
            key = k[len(namespace):]
        else:
            key = k
        if lowercase:
            key = key.lower()
        rv[key] = v
    return rv


get_namespace方法,是从指定的名称空间或前缀中进行匹配,返回包含配置项的子集的字典


迭代当前对象,获取key和v,把key转换为小写格式,然后把key和v包含在一个字典中


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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目