context.py 1.1 KB

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