完成配置加载

This commit is contained in:
moyanj 2024-09-09 15:03:46 +08:00
parent f1a392aa32
commit 36a5f9cfd3
5 changed files with 31 additions and 40 deletions

View File

@ -1,48 +1,33 @@
from typing import Union
from os import path as osp
import os import os
import importlib import json5
import time import app.env as env
class Config: class Config:
def __init__(self,conf:Union[dict,str]): def __init__(self):
self._conf_Dict = json5.load(os.path.join(env.dirs.user_config_path, "config.json"), encoding="utf-8")
if type(conf) == dict: self.__name__ = "<Standard Dictionary>"
# 杈撳叆鏄瓧鍏告椂
self._conf_Dict = conf
self.__name__ = '<Standard Dictionary>'
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() self.update()
def __getattr__(self, name): def __getattr__(self, name):
if name in self._conf_Dict: if name in self._conf_Dict:
return self._conf_Dict[name] return self._conf_Dict[name]
else: else:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{name}'"
)
def update(self,conf:Union[dict, None] = None): def update(self):
if conf: for k, v in self._conf_Dict.items():
self._conf_Dict = conf if isinstance(v, dict):
# 鏇存柊鍒楄〃 setattr(self, k, Config(v))
for k,v in self._conf_Dict.items(): elif isinstance(v, list):
setattr(self,k,v) setattr(
self.__updateTime__ = time.time() self,
k,
[Config(item) if isinstance(item, dict) else item for item in v],
)
else:
setattr(self, k, v)
c = Config('env://MY:dotenv') def __str__(self):
return str(self._conf_Dict)

0
app/endponit/HuTao.py Normal file
View File

1
app/endponit/__init__.py Normal file
View File

@ -0,0 +1 @@
from .HuTao import *

View File

@ -8,6 +8,10 @@ def init_dirs():
os.makedirs(dirs.user_log_path, exist_ok=True) os.makedirs(dirs.user_log_path, exist_ok=True)
os.makedirs(dirs.user_data_path, exist_ok=True) os.makedirs(dirs.user_data_path, exist_ok=True)
if not os.path.exists(os.path.join(dirs.user_config_path, "config.json")):
with open(os.path.join(dirs.user_config_path, "config.json"), "w") as f:
f.write("{}")
def init(): def init():
init_dirs() init_dirs()

View File

@ -1,3 +1,4 @@
pyqt5==5.15.11 pyqt5==5.15.11
PyQt-Fluent-Widgets[full]==1.6.3 PyQt-Fluent-Widgets[full]==1.6.3
platformdirs==4.3.1 platformdirs==4.3.1
json5==0.9.25