diff --git a/sentry_sdk/integrations/django/asgi.py b/sentry_sdk/integrations/django/asgi.py index 773c538045..e90b7e86d6 100644 --- a/sentry_sdk/integrations/django/asgi.py +++ b/sentry_sdk/integrations/django/asgi.py @@ -180,6 +180,10 @@ async def sentry_wrapped_callback(request, *args, **kwargs): if sentry_scope.profile is not None: sentry_scope.profile.update_active_thread_id() + integration = sentry_sdk.get_client().get_integration(DjangoIntegration) + if not integration or not integration.middleware_spans: + return await callback(request, *args, **kwargs) + with sentry_sdk.start_span( op=OP.VIEW_RENDER, name=request.resolver_match.view_name, diff --git a/sentry_sdk/integrations/django/views.py b/sentry_sdk/integrations/django/views.py index 0a9861a6a6..d832e342c7 100644 --- a/sentry_sdk/integrations/django/views.py +++ b/sentry_sdk/integrations/django/views.py @@ -49,7 +49,7 @@ def sentry_patched_make_view_atomic(self, *args, **kwargs): # efficient way to wrap views (or build a cache?) integration = sentry_sdk.get_client().get_integration(DjangoIntegration) - if integration is not None and integration.middleware_spans: + if integration is not None: is_async_view = ( iscoroutinefunction is not None and wrap_async_view is not None @@ -86,6 +86,10 @@ def sentry_wrapped_callback(request, *args, **kwargs): if sentry_scope.profile is not None: sentry_scope.profile.update_active_thread_id() + integration = sentry_sdk.get_client().get_integration(DjangoIntegration) + if not integration or not integration.middleware_spans: + return callback(request, *args, **kwargs) + with sentry_sdk.start_span( op=OP.VIEW_RENDER, name=request.resolver_match.view_name, diff --git a/tests/integrations/django/asgi/test_asgi.py b/tests/integrations/django/asgi/test_asgi.py index 8a30c7f5c0..f956d12f82 100644 --- a/tests/integrations/django/asgi/test_asgi.py +++ b/tests/integrations/django/asgi/test_asgi.py @@ -118,19 +118,25 @@ async def test_async_views(sentry_init, capture_events, application): @pytest.mark.parametrize("application", APPS) @pytest.mark.parametrize("endpoint", ["/sync/thread_ids", "/async/thread_ids"]) +@pytest.mark.parametrize("middleware_spans", [False, True]) @pytest.mark.asyncio @pytest.mark.forked @pytest.mark.skipif( django.VERSION < (3, 1), reason="async views have been introduced in Django 3.1" ) async def test_active_thread_id( - sentry_init, capture_envelopes, teardown_profiling, endpoint, application + sentry_init, + capture_envelopes, + teardown_profiling, + endpoint, + application, + middleware_spans, ): with mock.patch( "sentry_sdk.profiler.transaction_profiler.PROFILE_MINIMUM_SAMPLES", 0 ): sentry_init( - integrations=[DjangoIntegration()], + integrations=[DjangoIntegration(middleware_spans=middleware_spans)], traces_sample_rate=1.0, profiles_sample_rate=1.0, )