1+ import inspect
12from aikido_zen .context import get_current_context
23from .functions .asgi_middleware import InternalASGIMiddleware
34from ..helpers .get_argument import get_argument
4- from ..sinks import on_import , patch_function , before_async
5+ from ..sinks import on_import , patch_function , before_async , after
56
67
7- async def _asgi_app (func , instance , args , kwargs ):
8+ async def _call_coroutine (func , instance , args , kwargs ):
89 scope = get_argument (args , kwargs , 0 , "scope" )
910 receive = get_argument (args , kwargs , 1 , "receive" )
1011 send = get_argument (args , kwargs , 2 , "send" )
1112
1213 await InternalASGIMiddleware (func , "quart" )(scope , receive , send )
1314
1415
16+ @after
17+ def _call (func , instance , args , kwargs , return_value ):
18+ """
19+ Legacy ASGI v2.0
20+ func: application(scope)
21+ return_value: coroutine application_instance(receive, send)
22+ """
23+ scope = get_argument (args , kwargs , 0 , "scope" )
24+
25+ async def application_instance (receive , send ):
26+ await InternalASGIMiddleware (return_value , "quart" )(scope , receive , send )
27+
28+ # Modify return_value
29+ return_value = application_instance
30+
31+
1532@before_async
1633async def _handle_request_before (func , instance , args , kwargs ):
1734 context = get_current_context ()
@@ -37,9 +54,19 @@ async def _handle_request_before(func, instance, args, kwargs):
3754@on_import ("quart.app" , "quart" )
3855def patch (m ):
3956 """
40- patching module quart.app
41- - patches Quart.asgi_app (handles internal asgi middleware)
57+ We patch Quart.__call__ instead of asgi_app, because asgi_app itself can be wrapped multiple times
58+ And we want to be the first middleware to run.
59+ - patches Quart.__call__ (handles internal asgi middleware)
4260 - patches Quart.handle_request (Stores body/cookies)
4361 """
44- patch_function (m , "Quart.asgi_app" , _asgi_app )
62+
63+ if inspect .iscoroutine (m .Quart .__call__ ):
64+ # coroutine application(scope, receive, send)
65+ patch_function (m , "Quart.__call__" , _call_coroutine )
66+ else :
67+ # Legacy ASGI v2.0
68+ # https://asgi.readthedocs.io/en/latest/specs/main.html#legacy-applications
69+ # application(scope): coroutine application_instance(receive, send)
70+ patch_function (m , "Quart.__call__" , _call )
71+
4572 patch_function (m , "Quart.handle_request" , _handle_request_before )
0 commit comments