You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.py 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from functools import partial
  2. class BaseMiddleware:
  3. """
  4. Base class for implementing ASGI middleware. Inherit from this and
  5. override the setup() method if you want to do things before you
  6. get to.
  7. Note that subclasses of this are not self-safe; don't store state on
  8. the instance, as it serves multiple application instances. Instead, use
  9. scope.
  10. """
  11. def __init__(self, inner):
  12. """
  13. Middleware constructor - just takes inner application.
  14. """
  15. self.inner = inner
  16. def __call__(self, scope):
  17. """
  18. ASGI constructor; can insert things into the scope, but not
  19. run asynchronous code.
  20. """
  21. # Copy scope to stop changes going upstream
  22. scope = dict(scope)
  23. # Allow subclasses to change the scope
  24. self.populate_scope(scope)
  25. # Call the inner application's init
  26. inner_instance = self.inner(scope)
  27. # Partially bind it to our coroutine entrypoint along with the scope
  28. return partial(self.coroutine_call, inner_instance, scope)
  29. async def coroutine_call(self, inner_instance, scope, receive, send):
  30. """
  31. ASGI coroutine; where we can resolve items in the scope
  32. (but you can't modify it at the top level here!)
  33. """
  34. await self.resolve_scope(scope)
  35. await inner_instance(receive, send)