zhenxun_bot/utils/manager/data_class.py

111 lines
3.3 KiB
Python
Raw Normal View History

import copy
2021-11-23 21:44:59 +08:00
from pathlib import Path
from typing import Any, Dict, Generic, NoReturn, Optional, TypeVar, Union
2021-11-23 21:44:59 +08:00
import ujson as json
from ruamel import yaml
from ruamel.yaml import YAML
2021-11-23 21:44:59 +08:00
2022-11-21 20:43:41 +08:00
from .models import *
2022-06-21 21:01:14 +08:00
_yaml = YAML(typ="safe")
2021-11-23 21:44:59 +08:00
T = TypeVar("T")
2022-11-21 20:43:41 +08:00
class StaticData(Generic[T]):
2021-11-23 21:44:59 +08:00
"""
静态数据共享类
"""
2022-11-21 20:43:41 +08:00
def __init__(self, file: Optional[Path], load_file: bool = True):
2021-11-23 21:44:59 +08:00
self._data: dict = {}
if file:
file.parent.mkdir(exist_ok=True, parents=True)
self.file = file
2022-11-21 20:43:41 +08:00
if file.exists() and load_file:
2021-11-23 21:44:59 +08:00
with open(file, "r", encoding="utf8") as f:
if file.name.endswith("json"):
2021-12-16 11:16:28 +08:00
try:
self._data: dict = json.load(f)
except ValueError:
if f.read().strip():
raise ValueError(f"{file} 文件加载错误,请检查文件内容格式.")
2021-11-23 21:44:59 +08:00
elif file.name.endswith("yaml"):
2022-06-21 21:01:14 +08:00
self._data = _yaml.load(f)
2021-11-23 21:44:59 +08:00
def set(self, key, value):
2021-11-23 21:44:59 +08:00
self._data[key] = value
self.save()
def set_module_data(self, module, key, value, auto_save: bool = True):
2021-11-23 21:44:59 +08:00
if module in self._data.keys():
self._data[module][key] = value
2022-06-21 21:01:14 +08:00
if auto_save:
self.save()
2021-11-23 21:44:59 +08:00
2022-11-21 20:43:41 +08:00
def get(self, key) -> T:
2021-11-23 21:44:59 +08:00
return self._data.get(key)
2022-11-21 20:43:41 +08:00
def keys(self) -> List[str]:
2021-11-23 21:44:59 +08:00
return self._data.keys()
def delete(self, key):
2021-11-23 21:44:59 +08:00
if self._data.get(key) is not None:
del self._data[key]
2022-11-21 20:43:41 +08:00
def get_data(self) -> Dict[str, T]:
2022-04-04 20:33:37 +08:00
return copy.deepcopy(self._data)
2021-11-23 21:44:59 +08:00
2022-11-21 20:43:41 +08:00
def dict(self) -> Dict[str, Any]:
temp = {}
for k, v in self._data.items():
try:
temp[k] = v.dict()
except AttributeError:
temp[k] = copy.deepcopy(v)
return temp
2023-04-02 22:57:36 +08:00
def save(self, path: Optional[Union[str, Path]] = None):
2022-06-21 21:01:14 +08:00
path = path or self.file
2021-11-23 21:44:59 +08:00
if isinstance(path, str):
path = Path(path)
if path:
with open(path, "w", encoding="utf8") as f:
2022-06-21 21:01:14 +08:00
if path.name.endswith("yaml"):
2023-04-02 22:57:36 +08:00
yaml.dump(
self._data,
f,
indent=2,
Dumper=yaml.RoundTripDumper,
allow_unicode=True,
)
2022-06-21 21:01:14 +08:00
else:
2022-11-21 20:43:41 +08:00
json.dump(self.dict(), f, ensure_ascii=False, indent=4)
2021-11-23 21:44:59 +08:00
2023-04-02 22:57:36 +08:00
def reload(self):
2021-11-23 21:44:59 +08:00
if self.file.exists():
if self.file.name.endswith("json"):
self._data: dict = json.load(open(self.file, "r", encoding="utf8"))
elif self.file.name.endswith("yaml"):
2022-06-21 21:01:14 +08:00
self._data: dict = _yaml.load(open(self.file, "r", encoding="utf8"))
2021-11-23 21:44:59 +08:00
2022-11-21 20:43:41 +08:00
def is_exists(self) -> bool:
2021-11-23 21:44:59 +08:00
return self.file.exists()
2022-11-21 20:43:41 +08:00
def is_empty(self) -> bool:
2021-11-23 21:44:59 +08:00
return bool(len(self._data))
2022-11-21 20:43:41 +08:00
def __str__(self) -> str:
2021-11-23 21:44:59 +08:00
return str(self._data)
2023-04-02 22:57:36 +08:00
def __setitem__(self, key, value):
2021-11-23 21:44:59 +08:00
self._data[key] = value
2022-11-21 20:43:41 +08:00
def __getitem__(self, key) -> T:
2021-11-23 21:44:59 +08:00
return self._data[key]
def __len__(self) -> int:
return len(self._data)