context.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # (c) Nelen & Schuurmans
  2. from contextvars import ContextVar
  3. from fastapi import Request
  4. __all__ = ["ctx", "RequestMiddleware"]
  5. class Context:
  6. def __init__(self):
  7. self._request_value: ContextVar[Request] = ContextVar("request_value")
  8. @property
  9. def request(self) -> Request:
  10. return self._request_value.get()
  11. @request.setter
  12. def request(self, value: Request) -> None:
  13. self._request_value.set(value)
  14. ctx = Context()
  15. class RequestMiddleware:
  16. """Save the current request in a context variable.
  17. We were experiencing database connections piling up until PostgreSQL's
  18. max_connections was hit, which has to do with BaseHTTPMiddleware not
  19. interacting properly with context variables. For more details, see:
  20. https://github.com/tiangolo/fastapi/issues/4719. Writing this
  21. middleware as generic ASGI middleware fixes the problem.
  22. """
  23. def __init__(self, app):
  24. self.app = app
  25. async def __call__(self, scope, receive, send):
  26. if scope["type"] == "http":
  27. ctx.request = Request(scope, receive)
  28. await self.app(scope, receive, send)