refactor(files): 优化项目

- 重构files
- 新增yaml_processor(优化读取文件逻辑)
- 修复bug
This commit is contained in:
2025-03-05 18:11:28 +08:00
parent 698a95ac83
commit b8903798b8
11 changed files with 370 additions and 45 deletions

View File

@@ -10,7 +10,8 @@
@desc: 读取和保存yaml文件
"""
import logging
from dataclasses import dataclass, asdict, field
from pathlib import Path
import yaml
logger = logging.getLogger(__name__)
@@ -18,24 +19,42 @@ logger = logging.getLogger(__name__)
class YamlFile(dict):
def __init__(self, path):
super().__init__()
self.path = path
self.load()
super().__init__() # 初始化父类 dict
self.path = Path(path)
self.load() # 链式初始化加载
def load(self):
with open(self.path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) # 字典
if data:
self.update(data) # 把两个字段的内容合并
if self.path.exists():
with open(self.path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {} # 加载数据,空文件返回空字典
self.clear() # 清空当前实例
self.update(data) # 更新字典内容
else:
logger.warning(f"File {self.path} not found, initialized empty.")
return self # 链式调用
def to_yaml(self) -> str:
return yaml.safe_dump(
dict(self),
allow_unicode=True,
sort_keys=False
)
@classmethod
def by_yaml(cls, yaml_str):
data = yaml.safe_load(yaml_str) or {}
return cls({**data}) # 通过类方法创建实例
def save(self):
with open(self.path, "w", encoding="utf-8") as f:
yaml.safe_dump(
dict(self),
dict(self), # 直接 dump 实例本身(已继承 dict
stream=f,
allow_unicode=True, # allow_unicode使用unicode编码正常显示中文
sort_keys=False # sort_keys保持原有排序
allow_unicode=True,
sort_keys=False
)
return self # 链式调用
if __name__ == '__main__':