From aec8ee38464b40af00377f4686d2d8321b57f9e6 Mon Sep 17 00:00:00 2001 From: "Laurent Mignon (ACSONE)" Date: Fri, 6 Oct 2023 18:09:01 +0200 Subject: [PATCH] Openapi document with dependecies override with Pydantic V2 --- fastapi/_compat.py | 16 +++++++++++++++- fastapi/openapi/utils.py | 11 +++++++++++ tests/test_dependency_overrides_openapi.py | 5 ++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 4b07b44fa..677745eaa 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -161,7 +161,21 @@ if PYDANTIC_V2: def __hash__(self) -> int: # Each ModelField is unique for our purposes, to allow making a dict from # ModelField to its JSON Schema. - return id(self) + # build a hash from the field_info and name and mode + # This method is probably not safe enough... but how can + # we easily hash and compare ModelFields builds with the same data? + return hash( + ( + repr(self.field_info), + self.name, + self.mode, + ) + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ModelField): + return False + return self.__hash__() == other.__hash__() def get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index a27304fb6..b1e8e71d5 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -461,6 +461,17 @@ def get_fields_from_routes( if route.callbacks: callback_flat_models.extend(get_fields_from_routes(route.callbacks)) params = get_flat_params(route.dependant) + dependency_overrides = None + if route.dependency_overrides_provider: + dependency_overrides = ( + route.dependency_overrides_provider.dependency_overrides + ) + dependant = get_resolved_dependant( + dependant=route.dependant, + dependency_overrides=dependency_overrides, + ) + params.extend(get_flat_params(dependant)) + request_fields_from_routes.extend(params) flat_models = callback_flat_models + list( diff --git a/tests/test_dependency_overrides_openapi.py b/tests/test_dependency_overrides_openapi.py index 82bada04c..5d2640cd3 100644 --- a/tests/test_dependency_overrides_openapi.py +++ b/tests/test_dependency_overrides_openapi.py @@ -45,7 +45,10 @@ override_simple_openapi_schema = { "parameters": [ { "required": False, - "schema": {"title": "Q", "type": "string"}, + "schema": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Q", + }, "name": "q", "in": "query", },