Takes a function or coroutine `func(request) -> response`, and returns an ASGI application.
(
func: Callable[[Request], Awaitable[Response] | Response],
)
| 111 | # Copy of starlette.routing.request_response modified to include the |
| 112 | # dependencies' AsyncExitStack |
| 113 | def request_response( |
| 114 | func: Callable[[Request], Awaitable[Response] | Response], |
| 115 | ) -> ASGIApp: |
| 116 | """ |
| 117 | Takes a function or coroutine `func(request) -> response`, |
| 118 | and returns an ASGI application. |
| 119 | """ |
| 120 | f: Callable[[Request], Awaitable[Response]] = ( |
| 121 | func # type: ignore[assignment] |
| 122 | if is_async_callable(func) |
| 123 | else functools.partial(run_in_threadpool, func) # type: ignore[call-arg] |
| 124 | ) # ty: ignore[invalid-assignment] |
| 125 | |
| 126 | async def app(scope: Scope, receive: Receive, send: Send) -> None: |
| 127 | request = Request(scope, receive, send) |
| 128 | |
| 129 | async def app(scope: Scope, receive: Receive, send: Send) -> None: |
| 130 | # Starts customization |
| 131 | response_awaited = False |
| 132 | async with AsyncExitStack() as request_stack: |
| 133 | scope["fastapi_inner_astack"] = request_stack |
| 134 | async with AsyncExitStack() as function_stack: |
| 135 | scope["fastapi_function_astack"] = function_stack |
| 136 | response = await f(request) |
| 137 | await response(scope, receive, send) |
| 138 | # Continues customization |
| 139 | response_awaited = True |
| 140 | if not response_awaited: |
| 141 | raise FastAPIError( |
| 142 | "Response not awaited. There's a high chance that the " |
| 143 | "application code is raising an exception and a dependency with yield " |
| 144 | "has a block with a bare except, or a block with except Exception, " |
| 145 | "and is not raising the exception again. Read more about it in the " |
| 146 | "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" |
| 147 | ) |
| 148 | |
| 149 | # Same as in Starlette |
| 150 | await wrap_app_handling_exceptions(app, request)(scope, receive, send) |
| 151 | |
| 152 | return app |
| 153 | |
| 154 | |
| 155 | # Copy of starlette.routing.websocket_session modified to include the |