Browse Source

catch PydanticUndefinedAnnotation in create_response_field

this exception may be raised when having some unresolvable forward refs
most probably when trying to return a complex SQLAlchemy object
pull/11853/head
Mathieu Bressolle-Chataigner 9 months ago
parent
commit
ef0b8280ef
  1. 4
      fastapi/_compat.py
  2. 3
      fastapi/utils.py

4
fastapi/_compat.py

@ -47,6 +47,7 @@ sequence_types = tuple(sequence_annotation_to_type.keys())
if PYDANTIC_V2:
from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError
from pydantic.errors import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation
from pydantic import TypeAdapter
from pydantic import ValidationError as ValidationError
from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined]
@ -358,6 +359,9 @@ else:
class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef]
pass
class PydanticUndefinedAnnotation(Exception): # type: ignore[no-redef]
pass
def with_info_plain_validator_function( # type: ignore[misc]
function: Callable[..., Any],
*,

3
fastapi/utils.py

@ -20,6 +20,7 @@ from fastapi._compat import (
BaseConfig,
ModelField,
PydanticSchemaGenerationError,
PydanticUndefinedAnnotation,
Undefined,
UndefinedType,
Validator,
@ -97,7 +98,7 @@ def create_response_field(
)
try:
return ModelField(**kwargs) # type: ignore[arg-type]
except (RuntimeError, PydanticSchemaGenerationError):
except (RuntimeError, PydanticSchemaGenerationError, PydanticUndefinedAnnotation):
raise fastapi.exceptions.FastAPIError(
"Invalid args for response field! Hint: "
f"check that {type_} is a valid Pydantic field type. "

Loading…
Cancel
Save