Opened 4 years ago

Closed 4 years ago

#32093 closed New feature (wontfix)

Optional Async Middleware without Context Switching

Reported by: Andrew Chen Wang Owned by: nobody
Component: Utilities Version: dev
Severity: Normal Keywords: middleware
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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.

Change History (1)

comment:1 by Mariusz Felisiak, 4 years ago

Easy pickings: unset
Resolution: wontfix
Status: newclosed

MiddlewareMixin is just a deprecation shim to ease creating middleware classes, see docs. If you have concerns about context switching you should create a middleware without it, see docs.

Please check async topics and start a discussion on DevelopersMailingList before you will create more async-related tickets.

Note: See TracTickets for help on using tickets.
Back to Top