|
2 | 2 | from typing import Any, Callable, Coroutine, Dict, List, Optional, Sequence, Type, Union |
3 | 3 |
|
4 | 4 | from fastapi import routing |
5 | | -from fastapi.concurrency import AsyncExitStack |
6 | 5 | from fastapi.datastructures import Default, DefaultPlaceholder |
7 | 6 | from fastapi.encoders import DictIntStrAny, SetIntStr |
8 | 7 | from fastapi.exception_handlers import ( |
|
11 | 10 | ) |
12 | 11 | from fastapi.exceptions import RequestValidationError |
13 | 12 | from fastapi.logger import logger |
| 13 | +from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware |
14 | 14 | from fastapi.openapi.docs import ( |
15 | 15 | get_redoc_html, |
16 | 16 | get_swagger_ui_html, |
|
21 | 21 | from fastapi
9E88
.types import DecoratedCallable |
22 | 22 | from starlette.applications import Starlette |
23 | 23 | from starlette.datastructures import State |
24 | | -from starlette.exceptions import HTTPException |
| 24 | +from starlette.exceptions import ExceptionMiddleware, HTTPException |
25 | 25 | from starlette.middleware import Middleware |
| 26 | +from starlette.middleware.errors import ServerErrorMiddleware |
26 | 27 | from starlette.requests import Request |
27 | 28 | from starlette.responses import HTMLResponse, JSONResponse, Response |
28 | 29 | from starlette.routing import BaseRoute |
@@ -134,6 +135,55 @@ def __init__( |
134 | 135 | self.openapi_schema: Optional[Dict[str, Any]] = None |
135 | 136 | self.setup() |
136 | 137 |
|
| 138 | + def build_middleware_stack(self) -> ASGIApp: |
| 139 | + # Duplicate/override from Starlette to add AsyncExitStackMiddleware |
| 140 | + # inside of ExceptionMiddleware, inside of custom user middlewares |
| 141 | + debug = self.debug |
| 142 | + error_handler = None |
| 143 | + exception_handlers = {} |
| 144 | + |
| 145 | + for key, value in self.exception_handlers.items(): |
| 146 | + if key in (500, Exception): |
| 147 | + error_handler = value |
| 148 | + else: |
| 149 | + exception_handlers[key] = value |
| 150 | + |
| 151 | + middleware = ( |
| 152 | + [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] |
| 153 | + + self.user_middleware |
| 154 | + + [ |
| 155 | + Middleware( |
| 156 | + ExceptionMiddleware, handlers=exception_handlers, debug=debug |
| 157 | + ), |
| 158 | + # Add FastAPI-specific AsyncExitStackMiddleware for dependencies with |
| 159 | + # contextvars. |
| 160 | + # This needs to happen after user middlewares because those create a |
| 161 | + # new contextvars context copy by using a new AnyIO task group. |
| 162 | + # The initial part of dependencies with yield is executed in the |
| 163 | + # FastAPI code, inside all the middlewares, but the teardown part |
| 164 | + # (after yield) is executed in the AsyncExitStack in this middleware, |
| 165 | + # if the AsyncExitStack lived outside of the custom middlewares and |
| 166 | + # contextvars were set in a dependency with yield in that internal |
| 167 | + # contextvars context, the values would not be available in the |
| 168 | + # outside context of the AsyncExitStack. |
| 169 | + # By putting the middleware and the AsyncExitStack here, inside all |
| 170 | + # user middlewares, the code before and after yield in dependencies |
| 171 | + # with yield is executed in the same contextvars context, so all values |
| 172 | + # set in contextvars before yield is still available after yield as |
| 173 | + # would be expected. |
| 174 | + # Additionally, by having this AsyncExitStack here, after the |
| 175 | + # ExceptionMiddleware, now dependencies can catch handled exceptions, |
| 176 | + # e.g. HTTPException, to customize the teardown code (e.g. DB session |
| 177 | + # rollback). |
| 178 | + Middleware(AsyncExitStackMiddleware), |
| 179 | + ] |
| 180 | + ) |
| 181 | + |
| 182 | + app = self.router |
| 183 | + for cls, options in reversed(middleware): |
| 184 | + app = cls(app=app, **options) |
| 185 | + return app |
| 186 | + |
137 | 187 | def openapi(self) -> Dict[str, Any]: |
138 | 188 | if not self.openapi_schema: |
139 | 189 | self.openapi_schema = get_openapi( |
@@ -206,12 +256,7 @@ async def redoc_html(req: Request) -> HTMLResponse: |
206 | 256 | async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
207 | 257 | if self.root_path: |
208 | 258 | scope["root_path"] = self.root_path |
209 | | - if AsyncExitStack: |
210 | | - async with AsyncExitStack() as stack: |
211 | | - scope["fastapi_astack"] = stack |
212 | | - await super().__call__(scope, receive, send) |
213 | | - else: |
214 | | - await super().__call__(scope, receive, send) # pragma: no cover |
| 259 | + await super().__call__(scope, receive, send) |
215 | 260 |
|
216 | 261 | def add_api_route( |
217 | 262 | self, |
|
0 commit comments