config_base.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from typing import Any
  5. from collections.abc import Callable, Generator
  6. from datetime import timedelta, time
  7. from pydantic import BaseModel, datetime_parse
  8. from pydantic.fields import ModelField
  9. def format_timedelta(tdelta: timedelta):
  10. days = tdelta.days
  11. hours, rem = divmod(tdelta.seconds, 3600)
  12. minutes, seconds = divmod(rem, 60)
  13. return f"{days:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"
  14. class TimeDelta(timedelta):
  15. def __str__(self):
  16. return format_timedelta(self)
  17. def __repr__(self):
  18. return format_timedelta(self)
  19. @classmethod
  20. def __modify_schema__(
  21. cls, field_schema: dict[str, Any], field: ModelField | None
  22. ):
  23. if field:
  24. field_schema['type'] = 'time_delta'
  25. class ConfigBase(BaseModel):
  26. # 这个是导出json时候的配置,但是新的是导出dict,所以的无效
  27. class Config:
  28. json_encoders = {
  29. TimeDelta: format_timedelta
  30. }
  31. class MultiLine(str):
  32. # @classmethod
  33. # def __get_validators__(cls) -> Generator[Callable, None, None]:
  34. # yield cls.validate
  35. #
  36. # @classmethod
  37. # def validate(cls, value: str, field: ModelField):
  38. # return cls(value)
  39. @classmethod
  40. def __modify_schema__(
  41. cls, field_schema: dict[str, Any], field: ModelField | None
  42. ):
  43. if field:
  44. field_schema['type'] = 'multi_line'
  45. class Time(time):
  46. """
  47. 尝试将字符串转换为time对象, 但是不生效
  48. """
  49. @classmethod
  50. def __get_validators__(cls):
  51. yield cls.validate
  52. @classmethod
  53. def validate(cls, value):
  54. print('validate', value)
  55. if isinstance(value, str):
  56. hour, minute, second = map(int, value.split(":"))
  57. return cls(hour, minute, second)
  58. elif isinstance(value, time):
  59. return value
  60. else:
  61. raise ValueError("Invalid time format")
  62. # @classmethod
  63. # def __modify_schema__(
  64. # cls, field_schema: dict[str, Any], field: ModelField | None
  65. # ):
  66. # if field:
  67. # field_schema['type'] = 'time'