config_base.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. class ConfigBase(BaseModel):
  20. class Config:
  21. json_encoders = {
  22. TimeDelta: format_timedelta
  23. }
  24. class MultiLine(str):
  25. # @classmethod
  26. # def __get_validators__(cls) -> Generator[Callable, None, None]:
  27. # yield cls.validate
  28. #
  29. # @classmethod
  30. # def validate(cls, value: str, field: ModelField):
  31. # return cls(value)
  32. @classmethod
  33. def __modify_schema__(
  34. cls, field_schema: dict[str, Any], field: ModelField | None
  35. ):
  36. if field:
  37. field_schema['type'] = 'multi_line'
  38. class Time(time):
  39. """
  40. 尝试将字符串转换为time对象, 但是不生效
  41. """
  42. @classmethod
  43. def __get_validators__(cls):
  44. yield cls.validate
  45. @classmethod
  46. def validate(cls, value):
  47. print('validate', value)
  48. if isinstance(value, str):
  49. hour, minute, second = map(int, value.split(":"))
  50. return cls(hour, minute, second)
  51. elif isinstance(value, time):
  52. return value
  53. else:
  54. raise ValueError("Invalid time format")