用户设置:
# 自定义配置文件
USER = 'root'
PWD = '123'
全局配置
# 项目默认的配置文件
EMAIL = '1223@qq.com'
config定义类方法把配置里面的值更新到类方法里面:
import os
import importlib
# from config import settings
os.environ['CUSTOM_CONF'] = 'config.settings'
from lib.conf import global_settings
# from config import settings
class Settings():
def __init__(self):
## 方法一
# 集成自定义配置和全局的
# # 默认的全局配置
# for key in dir(global_settings):
# if key.isupper():
# v = getattr(global_settings, key)
# setattr(self, key, v)
# # 用户自定义配置
# for key in dir(settings):
# if key.isupper():
# v = getattr(settings, key)
# setattr(self, key, v)
# 方法二
#默认的全局配置
self.__setAttr(global_settings)
# 用户自定义的配置
constom_config = os.environ.get('CUSTOM_CONF')
settings = importlib.import_module(constom_config)
self.__setAttr(settings)
def __setAttr(self, conf):
for key in dir(conf):
if key.isupper():
v = getattr(conf, key)
setattr(self, key, v)
setting = Settings()
执行文件
import os
os.environ['CUSTOM_CONF'] = 'config.settings'
from lib.conf.config import setting
if __name__ == '__main__':
try:
print(os.environ)
print(setting.EMAIL)
print(setting.USER)
except Exception as e:
print('此配置不存在')