asyncexitstack.py 637 B

123456789101112131415161718
  1. from contextlib import AsyncExitStack
  2. from starlette.types import ASGIApp, Receive, Scope, Send
  3. # Used mainly to close files after the request is done, dependencies are closed
  4. # in their own AsyncExitStack
  5. class AsyncExitStackMiddleware:
  6. def __init__(
  7. self, app: ASGIApp, context_name: str = "fastapi_middleware_astack"
  8. ) -> None:
  9. self.app = app
  10. self.context_name = context_name
  11. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  12. async with AsyncExitStack() as stack:
  13. scope[self.context_name] = stack
  14. await self.app(scope, receive, send)