1
0
mirror of https://github.com/django/django.git synced 2025-06-03 18:49:12 +00:00

Refs #34118 -- Avoided repeat coroutine checks in MiddlewareMixin.

This commit is contained in:
Adam Johnson 2023-10-22 23:17:33 +01:00 committed by Mariusz Felisiak
parent 7fcf4f2f0f
commit e2922b0d5f

View File

@ -100,7 +100,13 @@ class MiddlewareMixin:
if get_response is None: if get_response is None:
raise ValueError("get_response must be provided.") raise ValueError("get_response must be provided.")
self.get_response = get_response 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__() super().__init__()
def __repr__(self): 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): def __call__(self, request):
# Exit out to async mode, if needed # Exit out to async mode, if needed
if iscoroutinefunction(self): if self.async_mode:
return self.__acall__(request) return self.__acall__(request)
response = None response = None
if hasattr(self, "process_request"): if hasattr(self, "process_request"):