config_base.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import re
  5. from datetime import timedelta, time, datetime
  6. from typing import Any
  7. from pydantic import BaseModel
  8. from pydantic import (BeforeValidator,
  9. PlainSerializer,
  10. WithJsonSchema)
  11. from typing_extensions import Annotated
  12. def format_timedelta(tdelta: timedelta):
  13. days = tdelta.days
  14. hours, rem = divmod(tdelta.seconds, 3600)
  15. minutes, seconds = divmod(rem, 60)
  16. return f"{days:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"
  17. def datadelta_validator(v: Any) -> timedelta:
  18. if isinstance(v, str):
  19. try:
  20. pattern = r'(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})'
  21. match = re.match(pattern, v)
  22. if match:
  23. days = int(match.group(1))
  24. hours = int(match.group(2))
  25. minutes = int(match.group(3))
  26. seconds = int(match.group(4))
  27. return TimeDelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
  28. return TimeDelta(days=1, hours=0, minutes=0, seconds=0)
  29. except ValueError:
  30. raise ValueError('Invalid interval value. Expected format: seconds')
  31. return v
  32. def datetime_validator(v: Any) -> datetime:
  33. if isinstance(v, str):
  34. return datetime.fromisoformat(v)
  35. return v
  36. def time_validator(v: Any) -> time:
  37. if isinstance(v, str):
  38. return time.fromisoformat(v)
  39. return v
  40. MultiLine = Annotated[str,
  41. WithJsonSchema({'type': 'multi_line'}),]
  42. TimeDelta = Annotated[timedelta,
  43. BeforeValidator(datadelta_validator),
  44. PlainSerializer(format_timedelta, return_type=str),
  45. WithJsonSchema({'type': 'time_delta'}),]
  46. DateTime = Annotated[datetime,
  47. BeforeValidator(datetime_validator),
  48. PlainSerializer(lambda v: v.strftime('%Y-%m-%d %H:%M:%S'), return_type=str),
  49. WithJsonSchema({'type': 'date_time'}),]
  50. Time = Annotated[time,
  51. BeforeValidator(time_validator),
  52. PlainSerializer(lambda v: v.strftime('%H:%M:%S'), return_type=str),
  53. WithJsonSchema({'type': 'time'}),]
  54. # ---------------------------------------------------------------------------------------------------------------------
  55. class ConfigBase(BaseModel):
  56. pass