"""Middleware utilities.""" from typing import Callable from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.types import Receive from starlette.types import Scope from starlette.types import Send class BaseMiddleware(BaseHTTPMiddleware): """The base middleware, used as a foundation for other middleware.""" async def __call__(self, scope: Scope, receive: Receive, send: Send): """When the middleware is called. Supresses no response errors if the connection was terminated. Args: scope (Scope): Scope of the request receive (Receive): Receive channel send (Send): Send channel """ try: await super().__call__(scope, receive, send) except RuntimeError as exc: if str(exc) == 'No response returned.': request = Request(scope, receive=receive) if await request.is_disconnected(): return raise async def dispatch(self, request: Request, call_next: Callable): """Dispach function. Purposely raises a NotImplementedError. Args: request (Request): Request to process. call_next (Callable): Middleware function to call next. """ raise NotImplementedError()