__init__.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import sys
  2. from typing import Any, Iterator, Protocol, Type
  3. if sys.version_info >= (3, 10): # pragma: no cover
  4. from typing import ParamSpec
  5. else: # pragma: no cover
  6. from typing_extensions import ParamSpec
  7. from starlette.types import ASGIApp, Receive, Scope, Send
  8. P = ParamSpec("P")
  9. class _MiddlewareClass(Protocol[P]):
  10. def __init__(self, app: ASGIApp, *args: P.args, **kwargs: P.kwargs) -> None:
  11. ... # pragma: no cover
  12. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  13. ... # pragma: no cover
  14. class Middleware:
  15. def __init__(
  16. self,
  17. cls: Type[_MiddlewareClass[P]],
  18. *args: P.args,
  19. **kwargs: P.kwargs,
  20. ) -> None:
  21. self.cls = cls
  22. self.args = args
  23. self.kwargs = kwargs
  24. def __iter__(self) -> Iterator[Any]:
  25. as_tuple = (self.cls, self.args, self.kwargs)
  26. return iter(as_tuple)
  27. def __repr__(self) -> str:
  28. class_name = self.__class__.__name__
  29. args_strings = [f"{value!r}" for value in self.args]
  30. option_strings = [f"{key}={value!r}" for key, value in self.kwargs.items()]
  31. args_repr = ", ".join([self.cls.__name__] + args_strings + option_strings)
  32. return f"{class_name}({args_repr})"