File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
aws_lambda_powertools/utilities/idempotency/serialization Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ from dataclasses import asdict , is_dataclass
2
+ from typing import Any , Dict , Type
3
+
4
+ from aws_lambda_powertools .utilities .idempotency .exceptions import (
5
+ IdempotencyModelTypeError ,
6
+ IdempotencyNoSerializationModelError ,
7
+ )
8
+ from aws_lambda_powertools .utilities .idempotency .serialization .base import (
9
+ BaseIdempotencyModelSerializer ,
10
+ BaseIdempotencySerializer ,
11
+ )
12
+
13
+ DataClass = Any
14
+
15
+
16
+ class DataclassSerializer (BaseIdempotencyModelSerializer ):
17
+ def __init__ (self , model : Type [DataClass ]):
18
+ """
19
+ Parameters
20
+ ----------
21
+ model: Model
22
+ A Pydantic model of the type to transform
23
+ """
24
+ self .__model : Type [DataClass ] = model
25
+
26
+ def to_dict (self , data : DataClass ) -> Dict :
27
+ return asdict (data )
28
+
29
+ def from_dict (self , data : Dict ) -> DataClass :
30
+ return self .__model (** data )
31
+
32
+ @classmethod
33
+ def instantiate (cls , model_type : Any ) -> BaseIdempotencySerializer :
34
+ if model_type is None :
35
+ raise IdempotencyNoSerializationModelError ("No serialization model was supplied" )
36
+
37
+ if not is_dataclass (model_type ):
38
+ raise IdempotencyModelTypeError ("Model type is not inherited of dataclass type" )
39
+ return cls (model = model_type )
You can’t perform that action at this time.
0 commit comments