Skip to content

Commit

Permalink
♻️ Refactor deciding if embed body fields, do not overwrite fields,…
Browse files Browse the repository at this point in the history
… compute once per router, refactor internals in preparation for Pydantic models in `Form`, `Query` and others (fastapi#12117)
  • Loading branch information
tiangolo authored Sep 5, 2024
1 parent 7213d42 commit aa21814
Show file tree
Hide file tree
Showing 7 changed files with 324 additions and 136 deletions.
15 changes: 15 additions & 0 deletions fastapi/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ def create_body_model(
BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload]
return BodyModel

def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
return [
ModelField(field_info=field_info, name=name)
for name, field_info in model.model_fields.items()
]

else:
from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX
from pydantic import AnyUrl as Url # noqa: F401
Expand Down Expand Up @@ -513,6 +519,9 @@ def create_body_model(
BodyModel.__fields__[f.name] = f # type: ignore[index]
return BodyModel

def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
return list(model.__fields__.values()) # type: ignore[attr-defined]


def _regenerate_error_with_loc(
*, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]
Expand All @@ -532,6 +541,12 @@ def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:


def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
origin = get_origin(annotation)
if origin is Union or origin is UnionType:
for arg in get_args(annotation):
if field_annotation_is_sequence(arg):
return True
return False
return _annotation_is_sequence(annotation) or _annotation_is_sequence(
get_origin(annotation)
)
Expand Down
Loading

0 comments on commit aa21814

Please sign in to comment.