From f1a392aa327993e8dc05ecda39a46c095587b5c8 Mon Sep 17 00:00:00 2001 From: moyanj <1561515308@qq.com> Date: Mon, 9 Sep 2024 14:24:51 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E5=AE=9E=E7=8E=B0=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/config.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 app/config.py diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..29e4a83 --- /dev/null +++ b/app/config.py @@ -0,0 +1,48 @@ +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') \ No newline at end of file