[Django] #32093: Optional Async Middleware without Context Switching

44 views
Skip to first unread message

Django

unread,
Oct 8, 2020, 10:25:23 PM10/8/20
to django-...@googlegroups.com
#32093: Optional Async Middleware without Context Switching
--------------------------------------------+----------------------------
Reporter: Andrew Chen Wang | Owner: nobody
Type: New feature | Status: new
Component: Utilities | Version: master
Severity: Normal | Keywords: middleware
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 1
UI/UX: 0 |
--------------------------------------------+----------------------------
Currently, the MiddlewareMixin when using `__acall__` performs
`sync_to_async` for both `process_request` and `process_response`. I think
we should allow Middleware implementation to set some property such that:

{{{
class MiddlewareMixin:
# Already defined
sync_capable = True
async_capable = True
# New
native_async = False

async def __acall__(self, request):
"""
Async version of __call__ that is swapped in when an async request
is running.
"""
response = None
if hasattr(self, 'process_request'):
if self.native_async:
response = await self.process_request(request)
else:
response = await sync_to_async(
self.process_request,
thread_sensitive=True,
)(request)
response = response or await self.get_response(request)
if hasattr(self, 'process_response'):
if self.native_async:
response = self.process_response(request, response)
else:
response = await sync_to_async(
self.process_response,
thread_sensitive=True,
)(request, response)
return response
}}}

in order to avoid context switching which will improve performance.

--
Ticket URL: <https://code.djangoproject.com/ticket/32093>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Reply all
Reply to author
Forward
0 new messages