mirror of https://github.com/tiangolo/fastapi.git
parent
23f5940e8b
commit
e04bae2286
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
Loading…
Reference in New Issue