summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorCarlton Gibson <carlton.gibson@noumenal.es>2023-02-14 14:06:42 +0100
committerCarlton Gibson <carlton.gibson@noumenal.es>2023-02-14 14:16:19 +0100
commitb7aab1fb3a41b13ab5d7e19ae9891ed02b9390ce (patch)
treed1ecca6ba8cd21e00a19bcb33edb5e2b543e3784 /docs
parentac8cf0ae76a825f8849a6bfb1cdf94b882ad43f6 (diff)
[4.2.x] Fixed #34328 -- Added async-only class-based middleware example.
Backport of ce8189eea007882bbe6db22f86b0965e718bd341 from main
Diffstat (limited to 'docs')
-rw-r--r--docs/topics/http/middleware.txt19
1 files changed, 19 insertions, 0 deletions
diff --git a/docs/topics/http/middleware.txt b/docs/topics/http/middleware.txt
index f0db49abe5..9a20106618 100644
--- a/docs/topics/http/middleware.txt
+++ b/docs/topics/http/middleware.txt
@@ -371,6 +371,25 @@ Here's an example of how to create a middleware function that supports both::
Thus, even if you are wrapping an async view, you may be called in sync
mode if there is other, synchronous middleware between you and the view.
+When using an asynchronous class-based middleware, you must ensure that
+instances are correctly marked as coroutine functions::
+
+ from asgiref.sync import iscoroutinefunction, markcoroutinefunction
+
+ class AsyncMiddleware:
+ async_capable = True
+ sync_capable = False
+
+ def __init__(self, get_response):
+ self.get_response = get_response
+ if iscoroutinefunction(self.get_response):
+ markcoroutinefunction(self)
+
+ async def __call__(self, request):
+ response = await self.get_response(request)
+ # Some logic ...
+ return response
+
.. _upgrading-middleware:
Upgrading pre-Django 1.10-style middleware