This repository is a personal exercise focused on transitioning the middlewares within the Piccolo API
from the async def dispatch(self, request, call_next)
style to async def __call__(self, scope, receive, send)
.
Here are some general procedures for transforming the middleware:
-
The middleware no longer needs to inherit from
starlette.middleware.base.BaseHTTPMiddleware
. Instead, replacesuper().__init__(app)
withself.app = app
. -
Remove the
dispatch
method. -
Add the
__call__
method, a Python dunder method, with the signatureasync def __call__(self, scope, receive, send)
. -
Retrieve required information from the
scope
(a dictionary).Starlette
provides helpful functions or data structures for this purpose. For example, therequest
object can be obtained fromrequest = starlette.requests.Request(scope)
. -
Instead of directly returning the response, obtain a response, call it with
scope, receive, send
,await
it, and then forcefullyreturn
. -
receive
andsend
are callable. Core business logic may need to be moved into these callables. -
Finally, remember to call
self.app
withscope, receive, send
,await
it, and then forcefullyreturn
. -
If you're open to adding the dependency, asgiref provides some useful type annotations.