Changes between Version 3 and Version 6 of Ticket #33716


Ignore:
Timestamp:
May 17, 2022, 8:35:31 PM (2 years ago)
Author:
abetkin
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #33716

    • Property Severity Release blockerNormal
    • Property Summary Async-capable middleware is not async-capableasync get_response can be a regular function too
  • Ticket #33716 – Description

    v3 v6  
    1 All the standard django middleware is marked as async-capable. As I understand that means that sync_to_async adapters will not be used if no other middleware is present.
    2 
    3 However, if you call an endpoint that is handled by an async view, somehow the adapters are still used, and middleware is executed in a separate thread.
    4 
    5 Moreover, if you add your custom middleware that is async_capable than it tries not to use adapters, and quickly fails:
    6 
    7 [[https://code.djangoproject.com/attachment/ticket/33716/bug.png]]
     1Here is what we have in MiddlewareMixin:
    82
    93{{{
    10 AttributeError: 'coroutine' object has no attribute 'get'
     4    def _async_check(self):
     5        """
     6        If get_response is a coroutine function, turns us into async mode so
     7        a thread is not consumed during a whole request.
     8        """
     9        if asyncio.iscoroutinefunction(self.get_response):
     10            # Mark the class as async-capable, but do the actual switch
     11            # inside __call__ to avoid swapping out dunder methods
     12            self._is_coroutine = asyncio.coroutines._is_coroutine
     13        else:
     14            self._is_coroutine = None
    1115}}}
    1216
    13 In this example this was XFrameOptionsMiddleware that failed
     17This checks if the next middleware is a coroutine, and if not fallbacks to sync mode. However, we already mark all async-capable middleware as such, why the redundancy?
    1418
    15 Github project illustrating this: https://github.com/pwtail/django_bug
     19A common usecase that is currently not supported:
    1620
    17 Is reproduced in thae main branch and in 4.0
     21
     22{{{
     23def MyMiddleware(get_response):
     24
     25    def middleware(request):
     26        # Do some stuff with request that does not involve I/O
     27        request.vip_user = True
     28        return get_response(request)
     29
     30    return middleware
     31
     32MyMiddleware.async_capable=True
     33}}}
     34
     35middleware(request) will return the response in sync case and a coroutine in the async case, despite being a regular function (because get_response is a coroutine function in the latter case).
     36
     37So I propose to remove the redundant _async_check
     38
     39Github project to see the error: https://github.com/pwtail/django_bug
Back to Top