config_model.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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_args(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. def gui_task(self, task: str) -> str:
  56. """
  57. 返回提供给gui显示的参数
  58. :param task:
  59. :return:
  60. """
  61. task_name = convert_to_underscore(task)
  62. task = getattr(self, task_name, None)
  63. if task is None:
  64. logger.error(f'{task_name} is no inexistence')
  65. return ''
  66. return task.json()
  67. if __name__ == "__main__":
  68. try:
  69. c = ConfigModel("oas3")
  70. except ValidationError as e:
  71. print(e)
  72. c = ConfigModel()
  73. print(c.json())
  74. # c.write_json('pydantic', c.schema())