config_base.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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, ValidationError
  8. from pydantic import (BeforeValidator,
  9. PlainSerializer,
  10. WithJsonSchema,
  11. field_serializer,
  12. SerializationInfo)
  13. from typing_extensions import Annotated
  14. def format_timedelta(tdelta: timedelta):
  15. days = tdelta.days
  16. hours, rem = divmod(tdelta.seconds, 3600)
  17. minutes, seconds = divmod(rem, 60)
  18. return f"{days:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"
  19. def datadelta_validator(v: Any) -> timedelta:
  20. if isinstance(v, str):
  21. try:
  22. pattern = r'(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})'
  23. match = re.match(pattern, v)
  24. if match:
  25. days = int(match.group(1))
  26. hours = int(match.group(2))
  27. minutes = int(match.group(3))
  28. seconds = int(match.group(4))
  29. return TimeDelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
  30. return TimeDelta(days=1, hours=0, minutes=0, seconds=0)
  31. except ValueError:
  32. raise ValueError('Invalid interval value. Expected format: seconds')
  33. return v
  34. def datetime_validator(v: Any) -> datetime:
  35. if isinstance(v, str):
  36. return datetime.fromisoformat(v)
  37. return v
  38. def time_validator(v: Any) -> time:
  39. if isinstance(v, str):
  40. return time.fromisoformat(v)
  41. return v
  42. MultiLine = Annotated[str,
  43. WithJsonSchema({'type': 'multi_line'}),]
  44. TimeDelta = Annotated[timedelta,
  45. BeforeValidator(datadelta_validator),
  46. PlainSerializer(format_timedelta, return_type=str),
  47. WithJsonSchema({'type': 'time_delta'}),]
  48. DateTime = Annotated[datetime,
  49. BeforeValidator(datetime_validator),
  50. PlainSerializer(lambda v: v.strftime('%Y-%m-%d %H:%M:%S'), return_type=str),
  51. WithJsonSchema({'type': 'date_time'}),]
  52. Time = Annotated[time,
  53. BeforeValidator(time_validator),
  54. PlainSerializer(lambda v: v.strftime('%H:%M:%S'), return_type=str),
  55. WithJsonSchema({'type': 'time'}),]
  56. # ---------------------------------------------------------------------------------------------------------------------
  57. @classmethod
  58. def serializer_exclude(cls, value: any, info: SerializationInfo):
  59. if info.context and info.context.get('hide', False):
  60. return 0xABCDEF
  61. return value
  62. def dynamic_hide(*fields: str,):
  63. return field_serializer(*fields)(serializer_exclude)
  64. class ConfigBase(BaseModel):
  65. def __init__(self, *args, **kwargs):
  66. try:
  67. super().__init__(*args, **kwargs)
  68. except ValidationError as exc:
  69. """
  70. During the initialization of the ConfigBase class,
  71. if a ValidationError occurs, the default value of the field is used to initialize the field,
  72. and the exception is re-raised after the initialization is complete.
  73. """
  74. exc_info = exc.errors()[0]
  75. val_error_type = exc_info.get('type', None)
  76. val_error_key = exc_info.get('loc', None)[0]
  77. if val_error_type not in ['greater_than_equal',
  78. 'greater_than',
  79. 'less_than',
  80. 'less_than_equal',]:
  81. raise exc
  82. from module.logger import logger
  83. try:
  84. default_value = self.model_fields[val_error_key].default
  85. kwargs[val_error_key] = self.model_fields[val_error_key].default
  86. logger.warning(f'Field {val_error_key} is out of range, using default value {default_value}')
  87. logger.warning(repr(exc))
  88. logger.warning(str(kwargs))
  89. super().__init__(*args, **kwargs)
  90. except Exception as e:
  91. raise