From e2922b0d5f18169d1d0115a6db5d2ed8c42d0692 Mon Sep 17 00:00:00 2001 From: Adam Johnson Date: Sun, 22 Oct 2023 23:17:33 +0100 Subject: [PATCH] Refs #34118 -- Avoided repeat coroutine checks in MiddlewareMixin. --- django/utils/deprecation.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/django/utils/deprecation.py b/django/utils/deprecation.py index 77ff6b1eaa..4d136dfa16 100644 --- a/django/utils/deprecation.py +++ b/django/utils/deprecation.py @@ -100,7 +100,13 @@ class MiddlewareMixin: if get_response is None: raise ValueError("get_response must be provided.") self.get_response = get_response - self._async_check() + # If get_response is a coroutine function, turns us into async mode so + # a thread is not consumed during a whole request. + self.async_mode = iscoroutinefunction(self.get_response) + if self.async_mode: + # Mark the class as async-capable, but do the actual switch inside + # __call__ to avoid swapping out dunder methods. + markcoroutinefunction(self) super().__init__() def __repr__(self): @@ -113,19 +119,9 @@ class MiddlewareMixin: ), ) - def _async_check(self): - """ - If get_response is a coroutine function, turns us into async mode so - a thread is not consumed during a whole request. - """ - if iscoroutinefunction(self.get_response): - # Mark the class as async-capable, but do the actual switch - # inside __call__ to avoid swapping out dunder methods - markcoroutinefunction(self) - def __call__(self, request): # Exit out to async mode, if needed - if iscoroutinefunction(self): + if self.async_mode: return self.__acall__(request) response = None if hasattr(self, "process_request"):