app_yaml.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from datetime import datetime
  2. from pathlib import Path
  3. from typing import List
  4. from pydantic import BaseModel
  5. from sqlmodel import SQLModel
  6. import yaml
  7. from config.settings import settings
  8. def save_yaml_dump(config: dict, save_as: Path) -> Path:
  9. """保存配置文件"""
  10. save_as.parent.mkdir(parents=True, exist_ok=True)
  11. with open(save_as, 'w', encoding='utf-8') as f:
  12. yaml.dump(
  13. config,
  14. f,
  15. Dumper=yaml.SafeDumper,
  16. allow_unicode=True,
  17. indent=2,
  18. sort_keys=False
  19. )
  20. return save_as
  21. class BaseYaml(BaseModel):
  22. """Yaml基类"""
  23. def save(self, save_as: Path=settings.APP_CONFIG) -> Path:
  24. """保存配置文件"""
  25. return save_yaml_dump(self.model_dump(), save_as)
  26. @classmethod
  27. def load(cls, file_path: Path=settings.APP_CONFIG) -> 'BaseYaml':
  28. """加载配置文件"""
  29. class Subscription(SQLModel):
  30. url: str
  31. file_path: str
  32. updated_at: datetime
  33. error: int
  34. detail: dict
  35. class AppYaml(BaseModel):
  36. subscriptions: List[Subscription] = []
  37. def save(self, save_as: Path=settings.APP_CONFIG) -> Path:
  38. """保存配置文件"""
  39. save_yaml_dump(self.model_dump(), save_as)
  40. return self.load(save_as)
  41. @classmethod
  42. def load(cls, file_path: Path=settings.APP_CONFIG) -> 'AppYaml':
  43. """加载配置文件"""
  44. with open(file_path, 'r', encoding='utf-8') as f:
  45. config = yaml.safe_load(f) or {}
  46. # print(type(config), config)
  47. return cls(**config)
  48. app_yaml = AppYaml.load()