【CMDB】高级配置
思路:
一份默认配置,一份用户自定义配置,将两者结合,自定义优先级大于默认配置
目录结构
''' 用户自定义的配置文件,settings.py ''' USER = 'xiaoming' PASSWORD = '123'
''' 系统默认配置文件,global_settings.py ''' TEL = '13012312345'
'''用户自定义配置和系统默认配置文件的统一 config.py''' import os import importlib from . import global_settings class Settings(object): def __init__(self): # 默认配置文件 for name in dir(global_settings): if name.isupper(): value = getattr(global_settings,name) setattr(self,name,value) # 自定义配置文件 settings_module = os.environ.get('USER_SETTINGS') if not settings_module: return # 导入模块 m = importlib.import_module(settings_module) for name in dir(m): if name.isupper(): value = getattr(m,name) setattr(self,name,value) settings = Settings()
''' start.py 使用变量 ''' import os os.environ['USER_SETTINGS'] = 'config.settings' if __name__ == '__main__': from lib.conf.config import settings print(settings.USER)