mirror of
https://github.com/fastapi/fastapi.git
synced 2026-09-08 19:41:04 -04:00
Compare commits
No files matched your search
@@ -40,11 +40,7 @@ jobs:
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
|
||||
with:
|
||||
limit-access-to-actor: true
|
||||
- uses: tiangolo/latest-changes@c9b73efbc8992ef1a401e4235ea307a8ca8a724b # 0.6.1
|
||||
- uses: tiangolo/latest-changes@8a940392f4c65274539453a5d5a76d9550203ac1 # 0.7.1
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
latest_changes_file: docs/en/docs/release-notes.md
|
||||
latest_changes_header: '## Latest Changes'
|
||||
end_regex: '^## '
|
||||
debug_logs: true
|
||||
label_header_prefix: '### '
|
||||
@@ -7,6 +7,41 @@ hide:
|
||||
|
||||
## Latest Changes
|
||||
|
||||
## 0.140.7 (2026-07-27)
|
||||
|
||||
### Refactors
|
||||
|
||||
* ⚡️ Avoid flattening dependencies for OpenAPI. PR [#16076](https://github.com/fastapi/fastapi/pull/16076) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆️ Upgrade latest-changes to 0.7.1. PR [#16077](https://github.com/fastapi/fastapi/pull/16077) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add OpenAPI dependency benchmarks. PR [#16075](https://github.com/fastapi/fastapi/pull/16075) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.140.6 (2026-07-27)
|
||||
|
||||
### Refactors
|
||||
|
||||
* ⚡️ Avoid flattening dependencies for request parameters, mainly for OpenAPI. PR [#16073](https://github.com/fastapi/fastapi/pull/16073) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.140.5 (2026-07-27)
|
||||
|
||||
### Refactors
|
||||
|
||||
* ⚡️ Avoid flattening dependencies for body fields. PR [#16071](https://github.com/fastapi/fastapi/pull/16071) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.140.4 (2026-07-27)
|
||||
|
||||
### Refactors
|
||||
|
||||
* ⚡️ Skip unused dependency repeat bookkeeping. PR [#16069](https://github.com/fastapi/fastapi/pull/16069) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.140.3 (2026-07-27)
|
||||
|
||||
### Refactors
|
||||
|
||||
* ⚡️ Avoid repeated dependency flattening in OpenAPI. PR [#16067](https://github.com/fastapi/fastapi/pull/16067) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.140.2 (2026-07-27)
|
||||
|
||||
### Refactors
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
|
||||
|
||||
__version__ = "0.140.2"
|
||||
__version__ = "0.140.7"
|
||||
|
||||
from starlette import status as status
|
||||
|
||||
|
||||
@@ -134,10 +134,6 @@ def _get_security_scheme(*, dependant: Dependant) -> SecurityBase:
|
||||
return unwrapped
|
||||
|
||||
|
||||
def _get_security_dependencies(*, dependant: Dependant) -> list[Dependant]:
|
||||
return [dep for dep in dependant.dependencies if _is_security_scheme(dependant=dep)]
|
||||
|
||||
|
||||
@lru_cache(maxsize=_CALLABLE_CLASSIFICATION_CACHE_SIZE)
|
||||
def _is_gen_callable_cached(call_identity: _CallIdentity) -> bool:
|
||||
call = call_identity.call
|
||||
|
||||
@@ -144,74 +144,14 @@ def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> De
|
||||
)
|
||||
|
||||
|
||||
def get_flat_dependant(
|
||||
dependant: Dependant,
|
||||
*,
|
||||
skip_repeats: bool = False,
|
||||
visited: list[DependencyCacheKey] | None = None,
|
||||
parent_oauth_scopes: list[str] | None = None,
|
||||
_uses_scopes_cache: _UsesScopesCache | None = None,
|
||||
) -> Dependant:
|
||||
if visited is None:
|
||||
visited = []
|
||||
if _uses_scopes_cache is None:
|
||||
_uses_scopes_cache = {}
|
||||
visited.append(
|
||||
_get_cache_key(
|
||||
dependant=dependant,
|
||||
uses_scopes_cache=_uses_scopes_cache,
|
||||
)
|
||||
)
|
||||
use_parent_oauth_scopes = (parent_oauth_scopes or []) + (
|
||||
_get_oauth_scopes(dependant=dependant)
|
||||
)
|
||||
|
||||
flat_dependant = Dependant(
|
||||
path_params=dependant.path_params.copy(),
|
||||
query_params=dependant.query_params.copy(),
|
||||
header_params=dependant.header_params.copy(),
|
||||
cookie_params=dependant.cookie_params.copy(),
|
||||
body_params=dependant.body_params.copy(),
|
||||
name=dependant.name,
|
||||
call=dependant.call,
|
||||
request_param_name=dependant.request_param_name,
|
||||
websocket_param_name=dependant.websocket_param_name,
|
||||
http_connection_param_name=dependant.http_connection_param_name,
|
||||
response_param_name=dependant.response_param_name,
|
||||
background_tasks_param_name=dependant.background_tasks_param_name,
|
||||
security_scopes_param_name=dependant.security_scopes_param_name,
|
||||
own_oauth_scopes=dependant.own_oauth_scopes,
|
||||
parent_oauth_scopes=use_parent_oauth_scopes,
|
||||
use_cache=dependant.use_cache,
|
||||
path=dependant.path,
|
||||
scope=dependant.scope,
|
||||
)
|
||||
for sub_dependant in dependant.dependencies:
|
||||
if (
|
||||
skip_repeats
|
||||
and _get_cache_key(
|
||||
dependant=sub_dependant,
|
||||
uses_scopes_cache=_uses_scopes_cache,
|
||||
)
|
||||
in visited
|
||||
):
|
||||
continue
|
||||
flat_sub = get_flat_dependant(
|
||||
sub_dependant,
|
||||
skip_repeats=skip_repeats,
|
||||
visited=visited,
|
||||
parent_oauth_scopes=_get_oauth_scopes(dependant=flat_dependant),
|
||||
_uses_scopes_cache=_uses_scopes_cache,
|
||||
)
|
||||
flat_dependant.dependencies.append(flat_sub)
|
||||
flat_dependant.path_params.extend(flat_sub.path_params)
|
||||
flat_dependant.query_params.extend(flat_sub.query_params)
|
||||
flat_dependant.header_params.extend(flat_sub.header_params)
|
||||
flat_dependant.cookie_params.extend(flat_sub.cookie_params)
|
||||
flat_dependant.body_params.extend(flat_sub.body_params)
|
||||
flat_dependant.dependencies.extend(flat_sub.dependencies)
|
||||
|
||||
return flat_dependant
|
||||
def _get_flat_body_params(dependant: Dependant) -> list[ModelField]:
|
||||
body_params: list[ModelField] = []
|
||||
dependants = [dependant]
|
||||
while dependants:
|
||||
current_dependant = dependants.pop()
|
||||
body_params.extend(current_dependant.body_params)
|
||||
dependants.extend(reversed(current_dependant.dependencies))
|
||||
return body_params
|
||||
|
||||
|
||||
def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]:
|
||||
@@ -227,11 +167,31 @@ def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]:
|
||||
|
||||
|
||||
def get_flat_params(dependant: Dependant) -> list[ModelField]:
|
||||
flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
|
||||
path_params = _get_flat_fields_from_params(flat_dependant.path_params)
|
||||
query_params = _get_flat_fields_from_params(flat_dependant.query_params)
|
||||
header_params = _get_flat_fields_from_params(flat_dependant.header_params)
|
||||
cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)
|
||||
path_params: list[ModelField] = []
|
||||
query_params: list[ModelField] = []
|
||||
header_params: list[ModelField] = []
|
||||
cookie_params: list[ModelField] = []
|
||||
visited: list[DependencyCacheKey] = []
|
||||
uses_scopes_cache: _UsesScopesCache = {}
|
||||
dependants = [dependant]
|
||||
while dependants:
|
||||
current_dependant = dependants.pop()
|
||||
cache_key = _get_cache_key(
|
||||
dependant=current_dependant,
|
||||
uses_scopes_cache=uses_scopes_cache,
|
||||
)
|
||||
if cache_key in visited:
|
||||
continue
|
||||
visited.append(cache_key)
|
||||
path_params.extend(current_dependant.path_params)
|
||||
query_params.extend(current_dependant.query_params)
|
||||
header_params.extend(current_dependant.header_params)
|
||||
cookie_params.extend(current_dependant.cookie_params)
|
||||
dependants.extend(reversed(current_dependant.dependencies))
|
||||
path_params = _get_flat_fields_from_params(path_params)
|
||||
query_params = _get_flat_fields_from_params(query_params)
|
||||
header_params = _get_flat_fields_from_params(header_params)
|
||||
cookie_params = _get_flat_fields_from_params(cookie_params)
|
||||
return path_params + query_params + header_params + cookie_params
|
||||
|
||||
|
||||
@@ -1038,8 +998,8 @@ async def request_body_to_args(
|
||||
return values, errors
|
||||
|
||||
|
||||
def get_body_field(
|
||||
*, flat_dependant: Dependant, name: str, embed_body_fields: bool
|
||||
def _get_body_field(
|
||||
*, body_params: list[ModelField], name: str, embed_body_fields: bool
|
||||
) -> ModelField | None:
|
||||
"""
|
||||
Get a ModelField representing the request body for a path operation, combining
|
||||
@@ -1051,34 +1011,30 @@ def get_body_field(
|
||||
This is **not** used to validate/parse the request body, that's done with each
|
||||
individual body parameter.
|
||||
"""
|
||||
if not flat_dependant.body_params:
|
||||
if not body_params:
|
||||
return None
|
||||
first_param = flat_dependant.body_params[0]
|
||||
first_param = body_params[0]
|
||||
if not embed_body_fields:
|
||||
return first_param
|
||||
model_name = "Body_" + name
|
||||
BodyModel = create_body_model(
|
||||
fields=flat_dependant.body_params, model_name=model_name
|
||||
)
|
||||
required = any(
|
||||
True for f in flat_dependant.body_params if f.field_info.is_required()
|
||||
)
|
||||
BodyModel = create_body_model(fields=body_params, model_name=model_name)
|
||||
required = any(True for f in body_params if f.field_info.is_required())
|
||||
BodyFieldInfo_kwargs: dict[str, Any] = {
|
||||
"annotation": BodyModel,
|
||||
"alias": "body",
|
||||
}
|
||||
if not required:
|
||||
BodyFieldInfo_kwargs["default"] = None
|
||||
if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params):
|
||||
if any(isinstance(f.field_info, params.File) for f in body_params):
|
||||
BodyFieldInfo: type[params.Body] = params.File
|
||||
elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params):
|
||||
elif any(isinstance(f.field_info, params.Form) for f in body_params):
|
||||
BodyFieldInfo = params.Form
|
||||
else:
|
||||
BodyFieldInfo = params.Body
|
||||
|
||||
body_param_media_types = [
|
||||
f.field_info.media_type
|
||||
for f in flat_dependant.body_params
|
||||
for f in body_params
|
||||
if isinstance(f.field_info, params.Body)
|
||||
]
|
||||
if len(set(body_param_media_types)) == 1:
|
||||
|
||||
+76
-20
@@ -3,6 +3,7 @@ import http.client
|
||||
import inspect
|
||||
import warnings
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal, cast
|
||||
|
||||
from fastapi import routing
|
||||
@@ -17,13 +18,14 @@ from fastapi._compat import (
|
||||
from fastapi.datastructures import DefaultPlaceholder, _Unset
|
||||
from fastapi.dependencies.models import (
|
||||
Dependant,
|
||||
_get_cache_key,
|
||||
_get_oauth_scopes,
|
||||
_get_security_dependencies,
|
||||
_get_security_scheme,
|
||||
_is_security_scheme,
|
||||
_UsesScopesCache,
|
||||
)
|
||||
from fastapi.dependencies.utils import (
|
||||
_get_flat_fields_from_params,
|
||||
get_flat_dependant,
|
||||
get_flat_params,
|
||||
get_validation_alias,
|
||||
)
|
||||
@@ -34,7 +36,7 @@ from fastapi.openapi.models import OpenAPI
|
||||
from fastapi.params import Body, ParamTypes
|
||||
from fastapi.responses import Response
|
||||
from fastapi.sse import _SSE_EVENT_SCHEMA
|
||||
from fastapi.types import ModelNameMap
|
||||
from fastapi.types import DependencyCacheKey, ModelNameMap
|
||||
from fastapi.utils import (
|
||||
deep_dict_update,
|
||||
generate_operation_id_for_path,
|
||||
@@ -83,13 +85,57 @@ status_code_ranges: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
def get_openapi_security_definitions(
|
||||
flat_dependant: Dependant,
|
||||
@dataclass
|
||||
class _OpenAPIDependencyData:
|
||||
path_params: list[ModelField] = field(default_factory=list)
|
||||
query_params: list[ModelField] = field(default_factory=list)
|
||||
header_params: list[ModelField] = field(default_factory=list)
|
||||
cookie_params: list[ModelField] = field(default_factory=list)
|
||||
security_dependencies: list[tuple[Dependant, list[str]]] = field(
|
||||
default_factory=list
|
||||
)
|
||||
|
||||
|
||||
def _get_openapi_dependency_data(dependant: Dependant) -> _OpenAPIDependencyData:
|
||||
dependency_data = _OpenAPIDependencyData()
|
||||
visited: list[DependencyCacheKey] = []
|
||||
uses_scopes_cache: _UsesScopesCache = {}
|
||||
dependants: list[tuple[Dependant, list[str], bool]] = [(dependant, [], True)]
|
||||
while dependants:
|
||||
current_dependant, parent_oauth_scopes, is_root = dependants.pop()
|
||||
cache_key = _get_cache_key(
|
||||
dependant=current_dependant,
|
||||
uses_scopes_cache=uses_scopes_cache,
|
||||
)
|
||||
if cache_key in visited:
|
||||
continue
|
||||
visited.append(cache_key)
|
||||
dependency_data.path_params.extend(current_dependant.path_params)
|
||||
dependency_data.query_params.extend(current_dependant.query_params)
|
||||
dependency_data.header_params.extend(current_dependant.header_params)
|
||||
dependency_data.cookie_params.extend(current_dependant.cookie_params)
|
||||
oauth_scopes = parent_oauth_scopes.copy()
|
||||
for scope in _get_oauth_scopes(dependant=current_dependant):
|
||||
if scope not in oauth_scopes:
|
||||
oauth_scopes.append(scope)
|
||||
if not is_root and _is_security_scheme(dependant=current_dependant):
|
||||
dependency_data.security_dependencies.append(
|
||||
(current_dependant, oauth_scopes)
|
||||
)
|
||||
dependants.extend(
|
||||
(sub_dependant, oauth_scopes, False)
|
||||
for sub_dependant in reversed(current_dependant.dependencies)
|
||||
)
|
||||
return dependency_data
|
||||
|
||||
|
||||
def _get_openapi_security_definitions(
|
||||
security_dependencies: list[tuple[Dependant, list[str]]],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
security_definitions = {}
|
||||
# Use a dict to merge scopes for same security scheme
|
||||
operation_security_dict: dict[str, list[str]] = {}
|
||||
for security_dependency in _get_security_dependencies(dependant=flat_dependant):
|
||||
for security_dependency, oauth_scopes in security_dependencies:
|
||||
security_scheme = _get_security_scheme(dependant=security_dependency)
|
||||
security_definition = jsonable_encoder(
|
||||
security_scheme.model,
|
||||
@@ -101,7 +147,7 @@ def get_openapi_security_definitions(
|
||||
# Merge scopes for the same security scheme
|
||||
if security_name not in operation_security_dict:
|
||||
operation_security_dict[security_name] = []
|
||||
for scope in _get_oauth_scopes(dependant=security_dependency):
|
||||
for scope in oauth_scopes:
|
||||
if scope not in operation_security_dict[security_name]:
|
||||
operation_security_dict[security_name].append(scope)
|
||||
operation_security = [
|
||||
@@ -112,7 +158,7 @@ def get_openapi_security_definitions(
|
||||
|
||||
def _get_openapi_operation_parameters(
|
||||
*,
|
||||
dependant: Dependant,
|
||||
dependency_data: _OpenAPIDependencyData,
|
||||
model_name_map: ModelNameMap,
|
||||
field_mapping: dict[
|
||||
tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any]
|
||||
@@ -120,11 +166,10 @@ def _get_openapi_operation_parameters(
|
||||
separate_input_output_schemas: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
parameters = []
|
||||
flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
|
||||
path_params = _get_flat_fields_from_params(flat_dependant.path_params)
|
||||
query_params = _get_flat_fields_from_params(flat_dependant.query_params)
|
||||
header_params = _get_flat_fields_from_params(flat_dependant.header_params)
|
||||
cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)
|
||||
path_params = _get_flat_fields_from_params(dependency_data.path_params)
|
||||
query_params = _get_flat_fields_from_params(dependency_data.query_params)
|
||||
header_params = _get_flat_fields_from_params(dependency_data.header_params)
|
||||
cookie_params = _get_flat_fields_from_params(dependency_data.cookie_params)
|
||||
parameter_groups = [
|
||||
(ParamTypes.path, path_params),
|
||||
(ParamTypes.query, query_params),
|
||||
@@ -132,8 +177,8 @@ def _get_openapi_operation_parameters(
|
||||
(ParamTypes.cookie, cookie_params),
|
||||
]
|
||||
default_convert_underscores = True
|
||||
if len(flat_dependant.header_params) == 1:
|
||||
first_field = flat_dependant.header_params[0]
|
||||
if len(dependency_data.header_params) == 1:
|
||||
first_field = dependency_data.header_params[0]
|
||||
if lenient_issubclass(first_field.field_info.annotation, BaseModel):
|
||||
default_convert_underscores = getattr(
|
||||
first_field.field_info, "convert_underscores", True
|
||||
@@ -284,21 +329,33 @@ def get_openapi_path(
|
||||
assert current_response_class, "A response class is needed to generate OpenAPI"
|
||||
route_response_media_type: str | None = current_response_class.media_type
|
||||
if route.include_in_schema:
|
||||
dependency_data = _get_openapi_dependency_data(route.dependant)
|
||||
all_route_params = [
|
||||
field
|
||||
for fields in (
|
||||
dependency_data.path_params,
|
||||
dependency_data.query_params,
|
||||
dependency_data.header_params,
|
||||
dependency_data.cookie_params,
|
||||
)
|
||||
for field in _get_flat_fields_from_params(fields)
|
||||
]
|
||||
for method in route.methods:
|
||||
operation = get_openapi_operation_metadata(
|
||||
route=route, method=method, operation_ids=operation_ids
|
||||
)
|
||||
parameters: list[dict[str, Any]] = []
|
||||
flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True)
|
||||
security_definitions, operation_security = get_openapi_security_definitions(
|
||||
flat_dependant=flat_dependant
|
||||
security_definitions, operation_security = (
|
||||
_get_openapi_security_definitions(
|
||||
security_dependencies=dependency_data.security_dependencies
|
||||
)
|
||||
)
|
||||
if operation_security:
|
||||
operation.setdefault("security", []).extend(operation_security)
|
||||
if security_definitions:
|
||||
security_schemes.update(security_definitions)
|
||||
operation_parameters = _get_openapi_operation_parameters(
|
||||
dependant=route.dependant,
|
||||
dependency_data=dependency_data,
|
||||
model_name_map=model_name_map,
|
||||
field_mapping=field_mapping,
|
||||
separate_input_output_schemas=separate_input_output_schemas,
|
||||
@@ -458,7 +515,6 @@ def get_openapi_path(
|
||||
deep_dict_update(openapi_response, process_response)
|
||||
openapi_response["description"] = description
|
||||
http422 = "422"
|
||||
all_route_params = get_flat_params(route.dependant)
|
||||
if (all_route_params or route.body_field) and not any(
|
||||
status in operation["responses"]
|
||||
for status in [http422, "4XX", "default"]
|
||||
|
||||
+9
-9
@@ -55,10 +55,10 @@ from fastapi.dependencies.models import (
|
||||
_is_gen_callable,
|
||||
)
|
||||
from fastapi.dependencies.utils import (
|
||||
_get_body_field,
|
||||
_get_flat_body_params,
|
||||
_should_embed_body_fields,
|
||||
get_body_field,
|
||||
get_dependant,
|
||||
get_flat_dependant,
|
||||
get_parameterless_sub_dependant,
|
||||
get_stream_item_type,
|
||||
get_typed_return_annotation,
|
||||
@@ -849,16 +849,16 @@ def _build_dependant_with_parameterless_dependencies(
|
||||
path: str,
|
||||
call: Callable[..., Any],
|
||||
dependencies: Sequence[params.Depends],
|
||||
) -> tuple[Dependant, Dependant, bool]:
|
||||
) -> tuple[Dependant, list[ModelField], bool]:
|
||||
dependant = get_dependant(path=path, call=call, scope="function")
|
||||
for depends in dependencies[::-1]:
|
||||
dependant.dependencies.insert(
|
||||
0,
|
||||
get_parameterless_sub_dependant(depends=depends, path=path),
|
||||
)
|
||||
flat_dependant = get_flat_dependant(dependant)
|
||||
embed_body_fields = _should_embed_body_fields(flat_dependant.body_params)
|
||||
return dependant, flat_dependant, embed_body_fields
|
||||
body_params = _get_flat_body_params(dependant)
|
||||
embed_body_fields = _should_embed_body_fields(body_params)
|
||||
return dependant, body_params, embed_body_fields
|
||||
|
||||
|
||||
class _RouteWithPath(Protocol):
|
||||
@@ -1090,15 +1090,15 @@ def _populate_api_route_state(
|
||||
assert callable(endpoint), "An endpoint must be a callable"
|
||||
(
|
||||
route.dependant,
|
||||
flat_dependant,
|
||||
body_params,
|
||||
route._embed_body_fields,
|
||||
) = _build_dependant_with_parameterless_dependencies(
|
||||
path=route.path_format,
|
||||
call=route.endpoint,
|
||||
dependencies=route.dependencies,
|
||||
)
|
||||
route.body_field = get_body_field(
|
||||
flat_dependant=flat_dependant,
|
||||
route.body_field = _get_body_field(
|
||||
body_params=body_params,
|
||||
name=route.unique_id,
|
||||
embed_body_fields=route._embed_body_fields,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.benchmarks.utils import (
|
||||
ROUTE_COUNT,
|
||||
ROUTE_PATH_PREFIX,
|
||||
create_openapi_app,
|
||||
generate_openapi,
|
||||
)
|
||||
|
||||
if "--codspeed" not in sys.argv:
|
||||
pytest.skip(
|
||||
"Benchmark tests are skipped by default; run with --codspeed.",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.timeout(60)
|
||||
def test_openapi_dependency_graph(benchmark) -> None:
|
||||
app = create_openapi_app()
|
||||
schema = benchmark(generate_openapi, app)
|
||||
dynamic_paths = [
|
||||
path for path in schema["paths"] if path.startswith(ROUTE_PATH_PREFIX)
|
||||
]
|
||||
assert len(dynamic_paths) == ROUTE_COUNT
|
||||
assert all(
|
||||
any(
|
||||
parameter["in"] == "query" and parameter["name"] == "query_value"
|
||||
for parameter in schema["paths"][path]["get"]["parameters"]
|
||||
)
|
||||
for path in dynamic_paths
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
from collections.abc import Callable
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import Depends, FastAPI
|
||||
|
||||
LAST_DEPENDENCY_INDEX = 100
|
||||
ROUTE_COUNT = 20
|
||||
ROUTE_PATH_PREFIX = "/openapi-route-"
|
||||
|
||||
|
||||
def create_openapi_app() -> FastAPI:
|
||||
app = FastAPI()
|
||||
dependencies: dict[int, Callable[..., Any]] = {}
|
||||
|
||||
def create_dependency(index: int) -> Callable[..., Any]:
|
||||
if index == LAST_DEPENDENCY_INDEX:
|
||||
|
||||
def dependency(query_value: int = index) -> str:
|
||||
return str(query_value)
|
||||
|
||||
dependency.__name__ = f"dependency_{index}"
|
||||
return dependency
|
||||
|
||||
next_dependency = dependencies[index + 1]
|
||||
|
||||
async def dependency(
|
||||
sub_dependency: Annotated[str, Depends(next_dependency)],
|
||||
query_value: int = index,
|
||||
) -> str:
|
||||
return f"{query_value} -> {sub_dependency}"
|
||||
|
||||
dependency.__name__ = f"dependency_{index}"
|
||||
return dependency
|
||||
|
||||
for index in reversed(range(LAST_DEPENDENCY_INDEX + 1)):
|
||||
dependencies[index] = create_dependency(index)
|
||||
|
||||
async def endpoint(
|
||||
value: Annotated[str, Depends(dependencies[0])],
|
||||
) -> dict[str, str]:
|
||||
return {"value": value}
|
||||
|
||||
for index in range(ROUTE_COUNT):
|
||||
app.add_api_route(f"{ROUTE_PATH_PREFIX}{index}", endpoint, methods=["GET"])
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def generate_openapi(app: FastAPI) -> dict[str, Any]:
|
||||
app.openapi_schema = None
|
||||
return app.openapi()
|
||||
@@ -0,0 +1,33 @@
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.benchmarks.utils import (
|
||||
ROUTE_COUNT,
|
||||
ROUTE_PATH_PREFIX,
|
||||
create_openapi_app,
|
||||
generate_openapi,
|
||||
)
|
||||
|
||||
if "--codspeed" not in sys.argv:
|
||||
pytest.skip(
|
||||
"Benchmark tests are skipped by default; run with --codspeed.",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.timeout(60)
|
||||
def test_openapi_dependency_graph(benchmark) -> None:
|
||||
app = create_openapi_app()
|
||||
schema = benchmark(generate_openapi, app)
|
||||
dynamic_paths = [
|
||||
path for path in schema["paths"] if path.startswith(ROUTE_PATH_PREFIX)
|
||||
]
|
||||
assert len(dynamic_paths) == ROUTE_COUNT
|
||||
assert all(
|
||||
any(
|
||||
parameter["in"] == "query" and parameter["name"] == "query_value"
|
||||
for parameter in schema["paths"][path]["get"]["parameters"]
|
||||
)
|
||||
for path in dynamic_paths
|
||||
)
|
||||
@@ -6,7 +6,6 @@ from fastapi.dependencies.models import (
|
||||
_get_cache_key,
|
||||
_get_computed_scope,
|
||||
_get_oauth_scopes,
|
||||
_get_security_dependencies,
|
||||
_get_security_scheme,
|
||||
_is_async_gen_callable,
|
||||
_is_async_gen_callable_cached,
|
||||
@@ -146,7 +145,6 @@ def test_derived_values_are_not_stored_on_dependant() -> None:
|
||||
assert _get_oauth_scopes(dependant=dependant) == []
|
||||
assert not _uses_scopes(dependant=dependant, cache=uses_scopes_cache)
|
||||
assert not _uses_scopes(dependant=dependant, cache=uses_scopes_cache)
|
||||
assert _get_security_dependencies(dependant=dependant) == []
|
||||
assert _get_computed_scope(dependant=dependant) is None
|
||||
assert _get_cache_key(dependant=dependant) == (async_dependency, (), "")
|
||||
|
||||
@@ -160,7 +158,6 @@ def test_security_scheme_helpers() -> None:
|
||||
|
||||
assert _is_security_scheme(dependant=security_dependant)
|
||||
assert _get_security_scheme(dependant=security_dependant) is security_scheme
|
||||
assert _get_security_dependencies(dependant=dependant) == [security_dependant]
|
||||
assert _uses_scopes(dependant=dependant)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user