經過字符串引入模塊下的屬性

flask中能夠配置一個字符串導入settings下的配置文件python

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

這裏就是來說解一下這個究竟是怎麼實現的。web

例:
這是just_xxx.py裏面的內容django

# -*- coding: utf-8 -*-
# @Time : 2019/6/17 上午 11:50
# @Author : lh
# @Email : 22@qq.com
# @File : just_xxx.py
# @Software: PyCharm


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

test_use.pyflask

# -*- coding: utf-8 -*-
# @Time : 2019/6/17 上午 11:52
# @Author : lh
# @Email : 2470937072@qq.com
# @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))

這是個人項目目錄
在這裏插入圖片描述app

這就是flask和django裏面的配置文件的實現原理了。svg

相關文章
相關標籤/搜索