from typing import Union from os import path as osp import os import importlib import time class Config: def __init__(self,conf:Union[dict,str]): if type(conf) == dict: # 杈撳叆鏄瓧鍏告椂 self._conf_Dict = conf self.__name__ = '' else: ConfList = conf.split('://') FileFormat = ConfList[0] FilePath = ConfList[1] if FileFormat not in ['json','yaml','py','env']: # 鍒ゆ柇鏂囦欢鏍煎紡 raise NameError(f'Unsupported file format:{FileFormat}') if not osp.exists(FilePath) and FileFormat not in ['env','py']: # 鍒ゆ柇鏂囦欢鏄惁瀛樺湪 raise FileExistsError('The configuration file path does not exist.') self.__name__ = osp.splitext(osp.basename(FilePath))[0] self._conf_Dict = self._readConf(FilePath,FileFormat) self.update() def __getattr__(self, name): if name in self._conf_Dict: return self._conf_Dict[name] else: raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") def update(self,conf:Union[dict, None] = None): if conf: self._conf_Dict = conf # 鏇存柊鍒楄〃 for k,v in self._conf_Dict.items(): setattr(self,k,v) self.__updateTime__ = time.time() c = Config('env://MY:dotenv')