forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpydantic.py
30 lines (23 loc) · 1002 Bytes
/
pydantic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from typing import Dict, Type
from pydantic import BaseModel
from aws_lambda_powertools.utilities.idempotency.serialization.base import BaseIdempotencySerializer
Model = BaseModel
class PydanticSerializer(BaseIdempotencySerializer):
def __init__(self, model: Type[Model]):
"""
Parameters
----------
model: Model
A Pydantic model of the type to transform
"""
self.__model: Type[Model] = model
def to_dict(self, data: Model) -> Dict:
if callable(getattr(data, "model_dump", None)):
# Support for pydantic V2
return data.model_dump() # type: ignore[unused-ignore,attr-defined]
return data.dict()
def from_dict(self, data: Dict) -> Model:
if callable(getattr(self.__model, "model_validate", None)):
# Support for pydantic V2
return self.__model.model_validate(data) # type: ignore[unused-ignore,attr-defined]
return self.__model.parse_obj(data)