from datetime import datetime from pathlib import Path from typing import List from pydantic import BaseModel from sqlmodel import SQLModel import yaml from config.settings import settings def save_yaml_dump(config: dict, save_as: Path) -> Path: """保存配置文件""" save_as.parent.mkdir(parents=True, exist_ok=True) with open(save_as, 'w', encoding='utf-8') as f: yaml.dump( config, f, Dumper=yaml.SafeDumper, allow_unicode=True, indent=2, sort_keys=False ) return save_as class BaseYaml(BaseModel): """Yaml基类""" def save(self, save_as: Path=settings.APP_CONFIG) -> Path: """保存配置文件""" return save_yaml_dump(self.model_dump(), save_as) @classmethod def load(cls, file_path: Path=settings.APP_CONFIG) -> 'BaseYaml': """加载配置文件""" class Subscription(SQLModel): url: str file_path: str updated_at: datetime error: int detail: dict class AppYaml(BaseModel): subscriptions: List[Subscription] = [] def save(self, save_as: Path=settings.APP_CONFIG) -> Path: """保存配置文件""" save_yaml_dump(self.model_dump(), save_as) return self.load(save_as) @classmethod def load(cls, file_path: Path=settings.APP_CONFIG) -> 'AppYaml': """加载配置文件""" with open(file_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f) or {} # print(type(config), config) return cls(**config) app_yaml = AppYaml.load()