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 10 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: if PYDANTIC_V2:
from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError
from pydantic.errors import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation
from pydantic import TypeAdapter from pydantic import TypeAdapter
from pydantic import ValidationError as ValidationError from pydantic import ValidationError as ValidationError
from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined]
@ -358,6 +359,9 @@ else:
class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef]
pass pass
class PydanticUndefinedAnnotation(Exception): # type: ignore[no-redef]
pass
def with_info_plain_validator_function( # type: ignore[misc] def with_info_plain_validator_function( # type: ignore[misc]
function: Callable[..., Any], function: Callable[..., Any],
*, *,

3
fastapi/utils.py

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

Loading…
Cancel
Save