通过字符串引入模块下的属性

flask中可以配置一个字符串导入settings下的配置文件

app.config.from_object("settings.ProductionConfig")

这里就是来讲解一下这个到底是怎么实现的。

例:
这是just_xxx.py里面的内容

# -*- coding: utf-8 -*-
# @Time    : 2019/6/17 上午 11:50
# @Author  : lh
# @Email   : [email protected]
# @File    : just_xxx.py
# @Software: PyCharm


class MyValue(object):
    VALUE1 = 'this is a vaule1'
    VALUE2 = 'this is a vaule2'

test_use.py

# -*- coding: utf-8 -*-
# @Time    : 2019/6/17 上午 11:52
# @Author  : lh
# @Email   : [email protected]
# @File    : test_use.py
# @Software: PyCharm
import importlib

my_path = 'test1.just_xxx.MyValue'

path, name = my_path.rsplit('.', maxsplit=1) # 进行反向切片。

a = importlib.import_module(path) # 获取<module 'test1.just_xxx' from 'I:\\flask_about\\flask_test1\\test1\\just_xxx.py'>

cls = getattr(a, name) # 使用反射
for key in dir(cls): # 遍历内容
    if key.isupper(): # 筛选大写的属性
        print(key, getattr(cls, key))

这是我的项目目录
在这里插入图片描述

这就是flask和django里面的配置文件的实现原理了。

发布了59 篇原创文章 · 获赞 18 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38091140/article/details/93532975