From e04bae22860e53e8c08f2c1cd476b8a7aa5b9b12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Wirtel?= Date: Wed, 27 Nov 2019 21:23:23 +0100 Subject: [PATCH] :bug: Fix the usage of custom_encoder for jsonable_encoder #714 (#715) --- fastapi/encoders.py | 4 +++- tests/test_jsonable_encoder.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index bececedae..25cd0b026 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -32,7 +32,9 @@ def jsonable_encoder( if exclude is not None and not isinstance(exclude, set): exclude = set(exclude) if isinstance(obj, BaseModel): - encoder = getattr(obj.Config, "json_encoders", custom_encoder) + encoder = getattr(obj.Config, "json_encoders", {}) + if custom_encoder: + encoder.update(custom_encoder) if PYDANTIC_1: obj_dict = obj.dict( include=include, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 0975430d7..97fbf6e6d 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -105,3 +105,18 @@ def test_encode_model_with_alias_raises(): def test_encode_model_with_alias(): model = ModelWithAlias(Foo="Bar") assert jsonable_encoder(model) == {"Foo": "Bar"} + + +def test_custom_encoders(): + class safe_datetime(datetime): + pass + + class MyModel(BaseModel): + dt_field: safe_datetime + + instance = MyModel(dt_field=safe_datetime.now()) + + encoded_instance = jsonable_encoder( + instance, custom_encoder={safe_datetime: lambda o: o.isoformat()} + ) + assert encoded_instance["dt_field"] == instance.dt_field.isoformat()