Skip to content

Commit 2009ddd

Browse files
committed
fix(event_handler): custom serializer recursive values
1 parent be7a4cc commit 2009ddd

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

aws_lambda_powertools/event_handler/openapi/encoders.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,9 @@ def jsonable_encoder( # noqa: PLR0911
115115
include=include,
116116
exclude=exclude,
117117
by_alias=by_alias,
118-
exclude_none=exclude_none,
119118
exclude_unset=exclude_unset,
119+
exclude_none=exclude_none,
120+
custom_serializer=custom_serializer,
120121
)
121122

122123
# Sequences
@@ -201,9 +202,14 @@ def _dump_dict(
201202
by_alias: bool = True,
202203
exclude_unset: bool = False,
203204
exclude_none: bool = False,
205+
custom_serializer: Optional[Callable[[Any], str]] = None,
204206
) -> Dict[str, Any]:
205207
"""
206208
Dump a dict to a dict, using the same parameters as jsonable_encoder
209+
210+
Parameters
211+
----------
212+
custom_serializer
207213
"""
208214
encoded_dict = {}
209215
allowed_keys = set(obj.keys())
@@ -222,12 +228,14 @@ def _dump_dict(
222228
by_alias=by_alias,
223229
exclude_unset=exclude_unset,
224230
exclude_none=exclude_none,
231+
custom_serializer=custom_serializer,
225232
)
226233
encoded_value = jsonable_encoder(
227234
value,
228235
by_alias=by_alias,
229236
exclude_unset=exclude_unset,
230237
exclude_none=exclude_none,
238+
custom_serializer=custom_serializer,
231239
)
232240
encoded_dict[encoded_key] = encoded_value
233241
return encoded_dict

tests/functional/event_handler/_pydantic/test_openapi_encoders.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,21 @@ class MyClass:
193193

194194
with pytest.raises(SerializationError, match="Unable to serialize the object*"):
195195
jsonable_encoder(MyClass())
196+
197+
198+
def test_openapi_encode_custom_serializer_nested_dict():
199+
# GIVEN a nested dictionary with a custom class
200+
class CustomClass(object):
201+
__slots__ = []
202+
203+
nested_dict = {"a": {"b": CustomClass()}}
204+
205+
# AND a custom serializer
206+
def serializer(value):
207+
return "serialized"
208+
209+
# WHEN we call jsonable_encoder with the nested dictionary and unserializable value
210+
result = jsonable_encoder(nested_dict, custom_serializer=serializer)
211+
212+
# THEN we should get the custom serializer output
213+
assert result == {"a": {"b": "serialized"}}

0 commit comments

Comments
 (0)