Skip to content

Commit ead7183

Browse files
committed
fix: use custom serializers for custom base model values
1 parent 8bc85c6 commit ead7183

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

aws_lambda_powertools/event_handler/openapi/encoders.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ def jsonable_encoder( # noqa: PLR0911
8181
exclude_unset=exclude_unset,
8282
exclude_none=exclude_none,
8383
exclude_defaults=exclude_defaults,
84+
custom_serializer=custom_serializer,
8485
)
8586

8687
# Dataclasses
@@ -171,6 +172,7 @@ def _dump_base_model(
171172
exclude_unset: bool = False,
172173
exclude_none: bool = False,
173174
exclude_defaults: bool = False,
175+
custom_serializer: Optional[Callable[[Any], str]] = None,
174176
):
175177
"""
176178
Dump a BaseModel object to a dict, using the same parameters as jsonable_encoder
@@ -192,6 +194,7 @@ def _dump_base_model(
192194
obj_dict,
193195
exclude_none=exclude_none,
194196
exclude_defaults=exclude_defaults,
197+
custom_serializer=custom_serializer,
195198
)
196199

197200

tests/functional/event_handler/_pydantic/test_openapi_encoders.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,28 @@ def serializer(value):
228228

229229
# THEN we should get the custom serializer output
230230
assert result == ["serialized"]
231+
232+
233+
def test_openapi_encode_custom_serializer_pydantic():
234+
# GIVEN a sequence with a custom class
235+
class CustomClass:
236+
__slots__ = []
237+
238+
class Order(BaseModel):
239+
kind: CustomClass
240+
241+
# maintenance: deprecate in V3; becomes model_config =ConfigDict(<directive>=True)
242+
class Config:
243+
arbitrary_types_allowed = True
244+
245+
order = Order(kind=CustomClass())
246+
247+
# AND a custom serializer
248+
def serializer(value):
249+
return "serialized"
250+
251+
# WHEN we call jsonable_encoder with the nested dictionary and unserializable value
252+
result = jsonable_encoder(order, custom_serializer=serializer)
253+
254+
# THEN we should get the custom serializer output
255+
assert result == {"kind": "serialized"}

0 commit comments

Comments
 (0)