|
1 | 1 | import datetime |
2 | | -from typing import Any, Callable |
| 2 | +from typing import Any, Callable, Optional |
3 | 3 |
|
| 4 | +import pydantic_core.core_schema |
4 | 5 | from pydantic import GetJsonSchemaHandler |
5 | 6 | from pydantic.json_schema import JsonSchemaValue |
6 | 7 | from pydantic_core import CoreSchema, core_schema |
7 | 8 |
|
8 | 9 | EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc) |
9 | 10 |
|
10 | 11 |
|
11 | | -class Epoch(datetime.datetime): |
| 12 | +class _Base(datetime.datetime): |
| 13 | + TYPE: str = '' |
| 14 | + CLS: Optional[Callable[[Any], Any]] |
| 15 | + SCHEMA: pydantic_core.core_schema.CoreSchema |
| 16 | + |
12 | 17 | @classmethod |
13 | 18 | def __get_pydantic_json_schema__( |
14 | 19 | cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler |
15 | 20 | ) -> JsonSchemaValue: |
16 | 21 | field_schema: dict[str, Any] = {} |
17 | | - field_schema.update(type='number', format='date-time') |
| 22 | + field_schema.update(type=cls.TYPE, format='date-time') |
18 | 23 | return field_schema |
19 | 24 |
|
20 | 25 | @classmethod |
21 | 26 | def __get_pydantic_core_schema__( |
22 | 27 | cls, source: type[Any], handler: Callable[[Any], CoreSchema] |
23 | 28 | ) -> core_schema.CoreSchema: |
24 | 29 | def f(value: Any, serializer: Callable[[datetime.datetime], float]) -> float: |
25 | | - return serializer(value.timestamp()) |
| 30 | + ts = value.timestamp() |
| 31 | + return serializer(cls.CLS(ts) if cls.CLS is not None else ts) |
26 | 32 |
|
27 | 33 | return core_schema.with_info_after_validator_function( |
28 | 34 | cls._validate, |
29 | | - core_schema.float_schema(), |
30 | | - serialization=core_schema.wrap_serializer_function_ser_schema(f, return_schema=core_schema.float_schema()), |
| 35 | + cls.SCHEMA, |
| 36 | + serialization=core_schema.wrap_serializer_function_ser_schema(f, return_schema=cls.SCHEMA), |
31 | 37 | ) |
32 | 38 |
|
33 | 39 | @classmethod |
34 | 40 | def _validate(cls, __input_value: Any, _: Any) -> datetime.datetime: |
35 | 41 | return EPOCH + datetime.timedelta(seconds=__input_value) |
| 42 | + |
| 43 | + |
| 44 | +class Number(_Base): |
| 45 | + TYPE = 'number' |
| 46 | + CLS = None |
| 47 | + SCHEMA = core_schema.float_schema() |
| 48 | + |
| 49 | + |
| 50 | +class Integer(_Base): |
| 51 | + TYPE = 'integer' |
| 52 | + CLS = int |
| 53 | + SCHEMA = core_schema.int_schema() |
0 commit comments