Browse Source

Support custom encoder fallback on older Pydantic

pull/15654/head
jiyujie2006 5 days ago
parent
commit
8f8177fa11
  1. 6
      fastapi/encoders.py
  2. 15
      tests/test_jsonable_encoder.py

6
fastapi/encoders.py

@ -265,7 +265,8 @@ def jsonable_encoder(
sqlalchemy_safe=sqlalchemy_safe,
)
obj_dict = obj.model_dump(
obj_dict = obj.__pydantic_serializer__.to_python(
obj,
mode="json",
include=include,
exclude=exclude,
@ -277,11 +278,8 @@ def jsonable_encoder(
)
return jsonable_encoder(
obj_dict,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_none=exclude_none,
exclude_defaults=exclude_defaults,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
obj_dict = obj.model_dump(

15
tests/test_jsonable_encoder.py

@ -284,6 +284,21 @@ def test_custom_encoder_model_field_uses_caller_options():
) == {"value": {"required": 1}}
def test_custom_encoder_model_field_does_not_encode_field_names():
class CustomValue:
pass
class ModelWithCustomValue(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
value: CustomValue
assert jsonable_encoder(
ModelWithCustomValue(value=CustomValue()),
custom_encoder={CustomValue: lambda _: "encoded", str: str.upper},
) == {"value": "ENCODED"}
def test_custom_enum_encoders():
def custom_enum_encoder(v: Enum):
return v.value.lower()

Loading…
Cancel
Save