|
| 1 | +from inspect import iscoroutinefunction |
1 | 2 | from inspect import isfunction |
2 | 3 | from types import FunctionType |
3 | 4 | from typing import Any |
@@ -134,17 +135,42 @@ def traced_auth_middleware_process_request(func: FunctionType, args: Tuple[Any], |
134 | 135 | def traced_middleware_factory(func: FunctionType, args: Tuple[Any], kwargs: Dict[str, Any]) -> Any: |
135 | 136 | middleware = func(*args, **kwargs) |
136 | 137 |
|
137 | | - if isfunction(middleware): |
138 | | - if hasattr(func, "__module__") and hasattr(func, "__qualname__"): |
139 | | - resource = f"{func.__module__}.{func.__qualname__}" |
140 | | - else: |
141 | | - resource = func_name(func) |
| 138 | + if not isfunction(middleware): |
| 139 | + return middleware |
| 140 | + |
| 141 | + if hasattr(func, "__module__") and hasattr(func, "__qualname__"): |
| 142 | + resource = f"{func.__module__}.{func.__qualname__}" |
| 143 | + else: |
| 144 | + resource = func_name(func) |
| 145 | + |
| 146 | + if iscoroutinefunction(middleware): |
| 147 | + # Handle async middleware - create async wrapper |
| 148 | + async def traced_async_middleware_func(*args, **kwargs): |
| 149 | + # The first argument for all middleware is the request object |
| 150 | + # DEV: Do `optional=true` to avoid raising an error for middleware that don't follow the convention |
| 151 | + # DEV: This is a function, so no `self` argument, so request is at position 0 |
| 152 | + request = get_argument_value(args, kwargs, 0, "request", optional=True) |
| 153 | + |
| 154 | + with core.context_with_data( |
| 155 | + "django.middleware.func", |
| 156 | + span_name="django.middleware", |
| 157 | + resource=resource, |
| 158 | + tags={ |
| 159 | + COMPONENT: config_django.integration_name, |
| 160 | + }, |
| 161 | + tracer=config_django._tracer, |
| 162 | + request=request, |
| 163 | + ): |
| 164 | + return await middleware(*args, **kwargs) |
142 | 165 |
|
| 166 | + return traced_async_middleware_func |
| 167 | + else: |
| 168 | + # Handle sync middleware - use original wrapping approach |
143 | 169 | def traced_middleware_func(func: FunctionType, args: Tuple[Any], kwargs: Dict[str, Any]) -> Any: |
144 | 170 | # The first argument for all middleware is the request object |
145 | 171 | # DEV: Do `optional=true` to avoid raising an error for middleware that don't follow the convention |
146 | 172 | # DEV: This is a function, so no `self` argument, so request is at position 0 |
147 | | - request = get_argument_value(args, kwargs, 0, "request") |
| 173 | + request = get_argument_value(args, kwargs, 0, "request", optional=True) |
148 | 174 |
|
149 | 175 | with core.context_with_data( |
150 | 176 | "django.middleware.func", |
|
0 commit comments