Handle JSON encoding Pydantic UndefinedType

This commit is contained in:
Andrew Williams 2023-07-22 23:46:04 +01:00
parent f7e3559bd5
commit 0e0b4a7b08
2 changed files with 10 additions and 2 deletions

View File

@ -23,7 +23,7 @@ from pydantic.color import Color
from pydantic.networks import NameEmail
from pydantic.types import SecretBytes, SecretStr
from ._compat import PYDANTIC_V2, MultiHostUrl, Url, _model_dump
from ._compat import PYDANTIC_V2, MultiHostUrl, UndefinedType, Url, _model_dump
# Taken from Pydantic v1 as is
@ -167,6 +167,8 @@ def jsonable_encoder(
return str(obj)
if isinstance(obj, (str, int, float, type(None))):
return obj
if isinstance(obj, UndefinedType):
return None
if isinstance(obj, dict):
encoded_dict = {}
allowed_keys = set(obj.keys())

View File

@ -7,7 +7,7 @@ from pathlib import PurePath, PurePosixPath, PureWindowsPath
from typing import Optional
import pytest
from fastapi._compat import PYDANTIC_V2
from fastapi._compat import PYDANTIC_V2, Undefined
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, Field, ValidationError
@ -309,3 +309,9 @@ def test_encode_deque_encodes_child_models():
dq = deque([Model(test="test")])
assert jsonable_encoder(dq)[0]["test"] == "test"
@needs_pydanticv2
def test_encode_pydantic_undefined():
data = {"value": Undefined}
assert jsonable_encoder(data) == {"value": None}