config_model.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import json
  5. from pathlib import Path
  6. from pydantic import BaseModel, ValidationError, validator, Field
  7. from module.config.utils import *
  8. from module.logger import logger
  9. # 导入配置的Python文件
  10. from module.tasks.Script.config import Script
  11. from module.tasks.Restart.config import Restart
  12. class ConfigModel(BaseModel):
  13. script: Script = Field(default_factory=Script)
  14. restart: Restart = Field(default_factory=Restart)
  15. # @validator('script')
  16. # def script_validator(cls, v):
  17. # if v is None:
  18. # return Script()
  19. def __init__(self, config_name: str) -> None:
  20. """
  21. :param config_name:
  22. """
  23. data = self.read_json(config_name)
  24. super().__init__(**data)
  25. @staticmethod
  26. def read_json(config_name: str) -> dict:
  27. """
  28. 读文件 没有额外操作
  29. :param config_name: 不带后缀
  30. :return:
  31. """
  32. filepath = Path.cwd() / "config" / f"{config_name}.json"
  33. return read_file(filepath)
  34. @staticmethod
  35. def write_json(config_name: str, data) -> None:
  36. """
  37. :param config_name: 不带后缀
  38. :param data: 字典而不是字符串
  39. :return:
  40. """
  41. filepath = Path.cwd() / "config" / f"{config_name}.json"
  42. write_file(filepath, data)
  43. def gui_task(self, task: str) -> str:
  44. """
  45. 返回提供给gui显示的参数
  46. :param task: 输入的是任务的名称英文 如'Script' 或者是'script'都是可以的
  47. :return: 返回的是pydantic给我们结构化的输出的信息, 如果不能获取就返回空的str
  48. """
  49. task = convert_to_underscore(task)
  50. task_gui = getattr(self, task, None)
  51. if task_gui is None:
  52. logger.error(f'{task} is no inexistence')
  53. return ''
  54. return task_gui.schema_json()
  55. if __name__ == "__main__":
  56. try:
  57. c = ConfigModel("oas3")
  58. except ValidationError as e:
  59. print(e)
  60. c = ConfigModel()
  61. print(c.json())
  62. # c.write_json('pydantic', c.schema())