Browse Source

Optimize APIRoute handler caching and fix endpoint context cache

pull/16021/head
RohaanDev 4 days ago
parent
commit
f9cbc553f7
  1. 259
      fastapi/routing.py

259
fastapi/routing.py

@ -9,6 +9,7 @@ import os
import stat
import threading
import types
import weakref
from collections.abc import (
AsyncIterator,
Awaitable,
@ -265,15 +266,17 @@ class _DefaultLifespan:
# Cache for endpoint context to avoid re-extracting on every request
_endpoint_context_cache: dict[int, EndpointContext] = {}
_endpoint_context_cache: "weakref.WeakKeyDictionary[Any, EndpointContext]" = (
weakref.WeakKeyDictionary()
)
def _extract_endpoint_context(func: Any) -> EndpointContext:
"""Extract endpoint context with caching to avoid repeated file I/O."""
func_id = id(func)
if func_id in _endpoint_context_cache:
return _endpoint_context_cache[func_id]
try:
return _endpoint_context_cache[func]
except (KeyError, TypeError):
pass
try:
ctx: EndpointContext = {}
@ -287,7 +290,10 @@ def _extract_endpoint_context(func: Any) -> EndpointContext:
except Exception:
ctx = EndpointContext()
_endpoint_context_cache[func_id] = ctx
try:
_endpoint_context_cache[func] = ctx
except TypeError:
pass
return ctx
@ -1257,11 +1263,14 @@ class APIRoute(routing.Route):
)
await response(scope, receive, send)
return
token = _effective_route_context_var.set(effective_context)
try:
app = request_response(self.get_route_handler())
finally:
_effective_route_context_var.reset(token)
app = effective_context._app
if app is None:
token = _effective_route_context_var.set(effective_context)
try:
app = request_response(self.get_route_handler())
finally:
_effective_route_context_var.reset(token)
effective_context._app = app
await app(scope, receive, send)
return
await super().handle(scope, receive, send)
@ -1363,6 +1372,7 @@ class _EffectiveRouteContext:
frontend_prefix: str = ""
path: str = ""
endpoint: Callable[..., Any] | None = None
_app: ASGIApp | None = field(default=None, repr=False, compare=False)
stream_item_type: Any | None = None
response_model: Any = None
summary: str | None = None
@ -3221,7 +3231,7 @@ class APIRouter(routing.Router):
"Did you mean to include a different router?"
)
assert not router._contains_router(self), (
"Cannot include an APIRouter instance that already includes this router. "
"Cannot include an APIRouter instance that already incluhis router. "
"Did you mean to include a different router?"
)
if prefix:
@ -3232,7 +3242,7 @@ class APIRouter(routing.Router):
else:
for route, route_context in _iter_routes_with_context(router.routes):
if route_context is None:
path = getattr(route, "path", None)
path = getattr(route, "p", None)
name = getattr(route, "name", "unknown")
elif route_context.starlette_route is not None:
path = getattr(route_context.starlette_route, "path", None)
@ -3242,7 +3252,7 @@ class APIRouter(routing.Router):
name = route_context.name
if path is not None and not path:
raise FastAPIError(
f"Prefix and path cannot be both empty (path operation: {name})"
f"Prefix and path cannot be both empty (path operation: {name})"
)
include_context = _RouterIncludeContext.for_include(
parent_router=self,
@ -3629,8 +3639,7 @@ class APIRouter(routing.Router):
summary=summary,
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
responses=responses, deprecated=deprecated,
methods=["GET"],
operation_id=operation_id,
response_model_include=response_model_include,
@ -3639,7 +3648,7 @@ class APIRouter(routing.Router):
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
inlude_in_schema=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
@ -3656,7 +3665,7 @@ class APIRouter(routing.Router):
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
"""
),
],
*,
@ -3673,14 +3682,14 @@ class APIRouter(routing.Router):
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
show it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
@ -3713,7 +3722,7 @@ class APIRouter(routing.Router):
"""
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
It will be added to the generated OpenAPI (e.g. visibt `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
@ -3727,7 +3736,7 @@ class APIRouter(routing.Router):
A list of dependencies (using `Depends()`) to be applied to the
*path operation*.
Read more about it in the
Read more about it the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
@ -3741,7 +3750,7 @@ class APIRouter(routing.Router):
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
astAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
"""
),
] = None,
@ -3769,7 +3778,7 @@ class APIRouter(routing.Router):
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
It will be added to the generated OpenAPe.g. visible at `/docs`).
"""
),
] = "Successful Response",
@ -3785,8 +3794,7 @@ class APIRouter(routing.Router):
] = None,
deprecated: Annotated[
bool | None,
Doc(
"""
Doc( """
Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
@ -3801,7 +3809,7 @@ class APIRouter(routing.Router):
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
If you provide a custom operation ID, you need to make s it is
unique for the whole API.
You can customize the
@ -3814,7 +3822,7 @@ class APIRouter(routing.Router):
),
] = None,
response_model_include: Annotated[
IncEx | None,
IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
@ -3827,7 +3835,7 @@ class APIRouter(routing.Router):
] = None,
response_model_exclude: Annotated[
IncEx | None,
Doc(
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
@ -3841,7 +3849,7 @@ class APIRouter(routing.Router):
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
Configuration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
@ -3853,7 +3861,7 @@ class APIRouter(routing.Router):
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
@ -3872,7 +3880,7 @@ class APIRouter(routing.Router):
Doc(
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
should have all the fields, including the ones that have thealue
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
they will be excluded from the response.
@ -3880,7 +3888,7 @@ class APIRouter(routing.Router):
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-paramet.
"""
),
] = False,
@ -3893,7 +3901,7 @@ class APIRouter(routing.Router):
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
those two instead of this one, those allow returning `None` values
when it makes sense.
Read more about it in the
@ -3907,7 +3915,7 @@ class APIRouter(routing.Router):
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
Thisaffects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
@ -3920,7 +3928,7 @@ class APIRouter(routing.Router):
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
@ -3933,7 +3941,7 @@ class APIRouter(routing.Router):
"""
Name for this *path operation*. Only used internally.
"""
),
,
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
@ -3947,7 +3955,7 @@ class APIRouter(routing.Router):
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
[FastAPI docs for OpenAPI Callbacks](https://fastapngolo.com/advanced/openapi-callbacks/).
"""
),
] = None,
@ -3959,7 +3967,7 @@ class APIRouter(routing.Router):
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-opi-path-operation-schema).
"""
),
] = None,
@ -3974,7 +3982,7 @@ class APIRouter(routing.Router):
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
@ -3989,7 +3997,7 @@ class APIRouter(routing.Router):
from pydantic import BaseModel
class Item(BaseModel):
name: str
name: str
description: str | None = None
app = FastAPI()
@ -4007,7 +4015,7 @@ class APIRouter(routing.Router):
response_model=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
dependencies=ncies,
summary=summary,
description=description,
response_description=response_description,
@ -4018,8 +4026,7 @@ class APIRouter(routing.Router):
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_unset=response_model_exclude_unset response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
@ -4060,13 +4067,13 @@ class APIRouter(routing.Router):
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
corresponding JSON. But if the data in tect returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
error and return a 500 error code (Internal Server Error).
@ -4997,7 +5004,7 @@ class APIRouter(routing.Router):
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
`response_modelde_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
@ -5018,7 +5025,7 @@ class APIRouter(routing.Router):
in that if the fields are set but contain the same default values,
they will be excluded from the response.
When `True`, default values are omitted from the response.
When , default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
@ -5030,7 +5037,7 @@ class APIRouter(routing.Router):
Doc(
"""
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
xclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
@ -5038,7 +5045,7 @@ class APIRouter(routing.Router):
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_no
"""
),
] = False,
@ -5065,7 +5072,7 @@ class APIRouter(routing.Router):
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
"""
"""
),
] = Default(JSONResponse),
name: Annotated[
@ -5082,7 +5089,7 @@ class APIRouter(routing.Router):
"""
List of *path operations* that will be used as OpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
This is only for OpenAPI documentation, callbacks won't be used
directly.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
@ -5108,7 +5115,7 @@ class APIRouter(routing.Router):
Callable[[APIRoute], str],
Doc(
"""
Customize the function used to generate unique IDs for the *path
Customize the function used to generunique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
@ -5235,7 +5242,7 @@ class APIRouter(routing.Router):
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
"""
"""
),
] = None,
dependencies: Annotated[
@ -5248,7 +5255,7 @@ class APIRouter(routing.Router):
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
),
] = None,
summary: Annotated[
str | None,
@ -5263,7 +5270,7 @@ class APIRouter(routing.Router):
"""
),
] = None,
description: Annotated[
description: Annotated
str | None,
Doc(
"""
@ -5294,7 +5301,7 @@ class APIRouter(routing.Router):
responses: Annotated[
dict[int | str, dict[str, Any]] | None,
Doc(
"""
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
@ -5309,8 +5316,7 @@ class APIRouter(routing.Router):
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
), ] = None,
operation_id: Annotated[
str | None,
Doc(
@ -5324,7 +5330,7 @@ class APIRouter(routing.Router):
You can customize the
operation ID generation with the parameter
`generate_unique_id_function` in the `FastAPI` class.
`generate_unique_id_function` in t`FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
@ -5338,7 +5344,7 @@ class APIRouter(routing.Router):
Configuration passed to Pydantic to include only certain fields in the
response data.
Read more about it in the
Reade about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
@ -5351,7 +5357,7 @@ class APIRouter(routing.Router):
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = None,
@ -5363,7 +5369,7 @@ class APIRouter(routing.Router):
should be serialized by alias when an alias is used.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
),
] = True,
@ -5373,7 +5379,7 @@ class APIRouter(routing.Router):
"""
Configuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
have their default This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
as the default.
@ -5406,7 +5412,7 @@ class APIRouter(routing.Router):
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data should
Contion passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
@ -5415,7 +5421,7 @@ class APIRouter(routing.Router):
when it makes sense.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
[FastAPI docs for Response Model - Return Type](ttps://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
"""
),
] = False,
@ -5428,7 +5434,7 @@ class APIRouter(routing.Router):
This affects the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
[FastAPI docs for Query Parameters and String Validations](https:astapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
"""
),
] = True,
@ -5441,7 +5447,7 @@ class APIRouter(routing.Router):
This will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
[FastAPI docs for Custom Response - HTML, Stream, File, others](//fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
"""
),
] = Default(JSONResponse),
@ -5457,7 +5463,7 @@ class APIRouter(routing.Router):
list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
List of *path operations* that will be used asOpenAPI callbacks.
This is only for OpenAPI documentation, the callbacks won't be used
directly.
@ -5472,7 +5478,7 @@ class APIRouter(routing.Router):
openapi_extra: Annotated[
dict[str, Any] | None,
Doc(
"""
"""
Extra metadata to be included in the OpenAPI schema for this *path
operation*.
@ -5494,8 +5500,7 @@ class APIRouter(routing.Router):
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
) ] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP HEAD operation.
@ -5514,7 +5519,7 @@ class APIRouter(routing.Router):
router = APIRouter()
@router.head("/items/", status_code=204)
def get_items_headers(response: Response):
def get_ims_headers(response: Response):
response.headers["X-Cat-Dog"] = "Alone in the world"
app.include_router(router)
@ -5530,7 +5535,7 @@ class APIRouter(routing.Router):
description=description,
response_description=response_description,
responses=responses,
deprecated=deprecated,
deprecated=deprecated,
methods=["HEAD"],
operation_id=operation_id,
response_model_include=response_model_include,
@ -5539,7 +5544,7 @@ class APIRouter(routing.Router):
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
include_ima=include_in_schema,
response_class=response_class,
name=name,
callbacks=callbacks,
@ -5556,7 +5561,7 @@ class APIRouter(routing.Router):
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
"""
),
],
*,
@ -5573,20 +5578,20 @@ class APIRouter(routing.Router):
It will be used for:
* Documentation: the generated OpenAPI (and the UI at `/docs`) will
show it as the response (JSON Schema).
ow it as the response (JSON Schema).
* Serialization: you could return an arbitrary object and the
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
not include that field, the JSON sent to the client would not have
that `password`.
* Validation: whatever you return will be serialized with the
`response_model`, converting any data as necessary to generate the
corresponding JSON. But if the data in the object returned is not
valid, that would mean a violation of the contract with the client,
so it's an error from the API developer. So, FastAPI will raise an
so it's an error from the API developer. So, FI will raise an
error and return a 500 error code (Internal Server Error).
Read more about it in the
@ -5600,7 +5605,7 @@ class APIRouter(routing.Router):
"""
The default status code to be used for the response.
You could override the status code by returning a response directly.
You could override the statcode by returning a response directly.
Read more about it in the
[FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
@ -5615,7 +5620,7 @@ class APIRouter(routing.Router):
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
"""
),
@ -5628,7 +5633,7 @@ class APIRouter(routing.Router):
*path operation*.
Read more about it in the
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
[FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
"""
),
] = None,
@ -5641,7 +5646,7 @@ class APIRouter(routing.Router):
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
[FastAPI docs fPath Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
"""
),
] = None,
@ -5656,7 +5661,7 @@ class APIRouter(routing.Router):
It can contain Markdown.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
It will be ad to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
@ -5669,7 +5674,7 @@ class APIRouter(routing.Router):
"""
The description for the default response.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
It will be added to the generated OpenAPI (e.g. visible at ocs`).
"""
),
] = "Successful Response",
@ -5686,8 +5691,7 @@ class APIRouter(routing.Router):
deprecated: Annotated[
bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
"" Mark this *path operation* as deprecated.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
"""
@ -5702,7 +5706,7 @@ class APIRouter(routing.Router):
By default, it is generated automatically.
If you provide a custom operation ID, you need to make sure it is
unique for the whole API.
unique for the whole API.
You can customize the
operation ID generation with the parameter
@ -5714,7 +5718,7 @@ class APIRouter(routing.Router):
),
] = None,
response_model_include: Annotated[
IncEx | None,
IncEx | No
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
@ -5728,7 +5732,7 @@ class APIRouter(routing.Router):
response_model_exclude: Annotated[
IncEx | None,
Doc(
"""
"""
Configuration passed to Pydantic to exclude certain fields in the
response data.
@ -5741,7 +5745,7 @@ class APIRouter(routing.Router):
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response model
Conguration passed to Pydantic to define if the response model
should be serialized by alias when an alias is used.
Read more about it in the
@ -5753,7 +5757,7 @@ class APIRouter(routing.Router):
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
figuration passed to Pydantic to define if the response data
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
@ -5780,8 +5784,7 @@ class APIRouter(routing.Router):
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """
),
] = False,
response_model_exclude_none: Annotated[
@ -5793,7 +5796,7 @@ class APIRouter(routing.Router):
This is much simpler (less smart) than `response_model_exclude_unset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
those two instead of this one, asse allow returning `None` values
when it makes sense.
Read more about it in the
@ -5807,7 +5810,7 @@ class APIRouter(routing.Router):
"""
Include this *path operation* in the generated OpenAPI schema.
This affects the generated OpenAPI (e.g. visible at `/docs`).
This affcts the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
@ -5820,7 +5823,7 @@ class APIRouter(routing.Router):
"""
Response class to be used for this *path operation*.
This will not be used if you return a response directly.
s will not be used if you return a response directly.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
@ -5834,7 +5837,7 @@ class APIRouter(routing.Router):
Name for this *path operation*. Only used internally.
"""
),
] = None,
] = None,
callbacks: Annotated[
list[BaseRoute] | None,
Doc(
@ -5847,7 +5850,7 @@ class APIRouter(routing.Router):
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Read more about it in the
[FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
[FastAPI docs for OpenAPI Callbacks](https://fastapi.tio.com/advanced/openapi-callbacks/).
"""
),
] = None,
@ -5859,7 +5862,7 @@ class APIRouter(routing.Router):
operation*.
Read more about it in the
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
[FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapth-operation-schema).
"""
),
] = None,
@ -5874,7 +5877,7 @@ class APIRouter(routing.Router):
SDKs for your API.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
"""
),
] = Default(generate_unique_id),
@ -5889,7 +5892,7 @@ class APIRouter(routing.Router):
from pydantic import BaseModel
class Item(BaseModel):
name: str
name: str
description: str | None = None
app = FastAPI()
@ -5919,7 +5922,7 @@ class APIRouter(routing.Router):
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
respone_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class,
@ -5935,7 +5938,7 @@ class APIRouter(routing.Router):
str,
Doc(
"""
The URL path to be used for this *path operation*.
The URL path to be used for this *path operation*.
For example, in `http://example.com/items`, the path is `/items`.
"""
@ -5950,7 +5953,7 @@ class APIRouter(routing.Router):
It could be any valid Pydantic *field* type. So, it doesn't have to
be a Pydantic model, it could be other things, like a `list`, `dict`,
etc.
etc.
It will be used for:
@ -5960,7 +5963,7 @@ class APIRouter(routing.Router):
`response_model` would be used to serialize that object into the
corresponding JSON.
* Filtering: the JSON sent to the client will only contain the data
(fields) defined in the `response_model`. If you returned an object
(fields) defi in the `response_model`. If you returned an object
that contains an attribute `password` but the `response_model` does
not include that field, the JSON sent to the client would not have
that `password`.
@ -5977,7 +5980,7 @@ class APIRouter(routing.Router):
),
] = Default(None),
status_code: Annotated[
int | None,
None,
Doc(
"""
The default status code to be used for the response.
@ -5993,7 +5996,7 @@ class APIRouter(routing.Router):
list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
A list of tags to be applied to the *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
@ -6018,7 +6021,7 @@ class APIRouter(routing.Router):
str | None,
Doc(
"""
A summary for the *path operation*.
A summary for the *path opera
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
@ -6033,7 +6036,7 @@ class APIRouter(routing.Router):
"""
A description for the *path operation*.
If not provided, it will be extracted automatically from the docstring
If not provided, it will be ected automatically from the docstring
of the *path operation function*.
It can contain Markdown.
@ -6047,7 +6050,7 @@ class APIRouter(routing.Router):
] = None,
response_description: Annotated[
str,
Doc(
Doc(
"""
The description for the default response.
@ -6061,7 +6064,7 @@ class APIRouter(routing.Router):
"""
Additional responses that could be returned by this *path operation*.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
It will be added to the generated OpenAPI (e.g. vat `/docs`).
"""
),
] = None,
@ -6079,7 +6082,7 @@ class APIRouter(routing.Router):
str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
Custom operation ID to be used by this *path otion*.
By default, it is generated automatically.
@ -6091,7 +6094,7 @@ class APIRouter(routing.Router):
`generate_unique_id_function` in the `FastAPI` class.
Read more about it in the
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
[FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-cs/#custom-generate-unique-id-function).
"""
),
] = None,
@ -6103,7 +6106,7 @@ class APIRouter(routing.Router):
response data.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-responsodel_exclude).
"""
),
] = None,
@ -6116,7 +6119,7 @@ class APIRouter(routing.Router):
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
"""
),
] = None,
response_model_by_alias: Annotated[
@ -6128,7 +6131,7 @@ class APIRouter(routing.Router):
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
"""
"""
),
] = True,
response_model_exclude_unset: Annotated[
@ -6139,7 +6142,7 @@ class APIRouter(routing.Router):
should have all the fields, including the ones that were not set and
have their default values. This is different from
`response_model_exclude_defaults` in that if the fields are set,
they will be included in the response, even if the value is the same
they will be included in the response, even the value is the same
as the default.
When `True`, default values are omitted from the response.
@ -6153,7 +6156,7 @@ class APIRouter(routing.Router):
bool,
Doc(
"""
Configuration passed to Pydantic to define if the response data
onfiguration passed to Pydantic to define if the response data
should have all the fields, including the ones that have the same value
as the default. This is different from `response_model_exclude_unset`
in that if the fields are set but contain the same default values,
@ -6162,7 +6165,7 @@ class APIRouter(routing.Router):
When `True`, default values are omitted from the response.
Read more about it in the
[FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
PI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
"""
),
] = False,
@ -6173,7 +6176,7 @@ class APIRouter(routing.Router):
Configuration passed to Pydantic to define if the response data should
exclude fields set to `None`.
This is much simpler (less smart) than `response_model_exclude_unset`
This is much simpler (less smart) than `response_model_excluunset`
and `response_model_exclude_defaults`. You probably want to use one of
those two instead of this one, as those allow returning `None` values
when it makes sense.
@ -6184,7 +6187,7 @@ class APIRouter(routing.Router):
),
] = False,
include_in_schema: Annotated[
bool,
ool,
Doc(
"""
Include this *path operation* in the generated OpenAPI schema.
@ -6210,7 +6213,7 @@ class APIRouter(routing.Router):
),
] = Default(JSONResponse),
name: Annotated[
str | None,
str e,
Doc(
"""
Name for this *path operation*. Only used internally.
@ -6252,7 +6255,7 @@ class APIRouter(routing.Router):
Customize the function used to generate unique IDs for the *path
operations* shown in the generated OpenAPI.
This is particularly useful when automatically generating clients or
This is particularly useful when automatically generating clients or
SDKs for your API.
Read more about it in the
@ -6262,9 +6265,7 @@ class APIRouter(routing.Router):
] = Default(generate_unique_id),
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Add a *path operation* using an HTTP TRACE operation.
## Example
Add a *path operation* using an HTTP TRACE operation. ## Example
```python
from fastapi import APIRouter, FastAPI
@ -6286,7 +6287,7 @@ class APIRouter(routing.Router):
"""
return self.api_route(
path=path,
response_model=response_model,
response_m=response_model,
status_code=status_code,
tags=tags,
dependencies=dependencies,
@ -6338,7 +6339,7 @@ class APIRouter(routing.Router):
Ref: https://github.com/Kludex/starlette/pull/3117
"""
for handler in self.on_shutdown:
if is_async_callable(handler):
if is_async_callabl(handler):
await handler()
else:
handler()

Loading…
Cancel
Save