22
33from ..functions .request_handler import request_handler
44from .run_init_stage import run_init_stage
5- from .pre_response_middleware import pre_response_middleware
5+ from .pre_response_middleware import (
6+ pre_response_middleware ,
7+ pre_response_middleware_async ,
8+ )
69from ...helpers .get_argument import get_argument
7- from ...sinks import on_import , patch_function , before , after
10+ from ...sinks import on_import , patch_function , before , after , before_async , after_async
811
912
1013@before
@@ -25,13 +28,32 @@ def _get_response_after(func, instance, args, kwargs, return_value):
2528 request_handler (stage = "post_response" , status_code = return_value .status_code )
2629
2730
31+ @before_async
32+ async def _get_response_async_before (func , instance , args , kwargs ):
33+ request = get_argument (args , kwargs , 0 , "request" )
34+
35+ run_init_stage (request )
36+
37+ if pre_response_middleware_async not in getattr (instance , "_view_middleware" ):
38+ # pylint:disable=protected-access
39+ instance ._view_middleware += [pre_response_middleware_async ]
40+
41+
42+ @after_async
43+ async def _get_response_async_after (func , instance , args , kwargs , return_value ):
44+ if hasattr (return_value , "status_code" ):
45+ request_handler (stage = "post_response" , status_code = return_value .status_code )
46+
47+
2848@on_import ("django.core.handlers.base" , "django" )
2949def patch (m ):
3050 """
31- Patch for _get_response (Synchronous/ WSGI)
51+ Patch for _get_response (WSGI) and _get_response_async (ASGI )
3252 - before: Parse body, create context & add middleware to run before a response
33- - after: Check respone code to see if route should be analyzed
53+ - after: Check response code to see if route should be analyzed
3454 # https://github.com/django/django/blob/5865ff5adcf64da03d306dc32b36e87ae6927c85/django/core/handlers/base.py#L174
3555 """
3656 patch_function (m , "BaseHandler._get_response" , _get_response_before )
3757 patch_function (m , "BaseHandler._get_response" , _get_response_after )
58+ patch_function (m , "BaseHandler._get_response_async" , _get_response_async_before )
59+ patch_function (m , "BaseHandler._get_response_async" , _get_response_async_after )
0 commit comments