zhenxun_bot/utils/manager/data_class.py

87 lines
2.7 KiB
Python
Raw Normal View History

2021-11-23 21:44:59 +08:00
from typing import Union, Optional
from pathlib import Path
from ruamel.yaml import YAML
2022-06-21 21:01:14 +08:00
from ruamel import yaml
2021-11-23 21:44:59 +08:00
import ujson as json
2022-04-04 20:33:37 +08:00
import copy
2021-11-23 21:44:59 +08:00
2022-06-21 21:01:14 +08:00
_yaml = YAML(typ="safe")
2021-11-23 21:44:59 +08:00
class StaticData:
"""
静态数据共享类
"""
def __init__(self, file: Optional[Path]):
self._data: dict = {}
if file:
file.parent.mkdir(exist_ok=True, parents=True)
self.file = file
if file.exists():
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):
self._data[key] = value
self.save()
2022-06-21 21:01:14 +08:00
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
def get(self, key):
return self._data.get(key)
def keys(self):
return self._data.keys()
def delete(self, key):
if self._data.get(key) is not None:
del self._data[key]
def get_data(self) -> dict:
2022-04-04 20:33:37 +08:00
return copy.deepcopy(self._data)
2021-11-23 21:44:59 +08:00
def save(self, path: 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"):
yaml.dump(self._data, f, indent=2, Dumper=yaml.RoundTripDumper, allow_unicode=True)
else:
json.dump(self._data, f, ensure_ascii=False, indent=4)
2021-11-23 21:44:59 +08:00
def reload(self):
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
def is_exists(self):
return self.file.exists()
def is_empty(self):
return bool(len(self._data))
def __str__(self):
return str(self._data)
def __setitem__(self, key, value):
self._data[key] = value
def __getitem__(self, key):
return self._data[key]