🐛 Fix the usage of custom_encoder for jsonable_encoder #714 (#715)

This commit is contained in:
Stéphane Wirtel 2019-11-27 21:23:23 +01:00 committed by Sebastián Ramírez
parent 23f5940e8b
commit e04bae2286
2 changed files with 18 additions and 1 deletions

View File

@ -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,

View File

@ -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()