summaryrefslogtreecommitdiffstats
path: root/third_party/python/sentry-sdk/sentry_sdk/integrations/django/asgi.py
blob: 96ae3e0809680a8616406321cb52489afc92eb8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Instrumentation for Django 3.0

Since this file contains `async def` it is conditionally imported in
`sentry_sdk.integrations.django` (depending on the existence of
`django.core.handlers.asgi`.
"""

from sentry_sdk import Hub
from sentry_sdk._types import MYPY

from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware

if MYPY:
    from typing import Any


def patch_django_asgi_handler_impl(cls):
    # type: (Any) -> None
    old_app = cls.__call__

    async def sentry_patched_asgi_handler(self, scope, receive, send):
        # type: (Any, Any, Any, Any) -> Any
        if Hub.current.get_integration(DjangoIntegration) is None:
            return await old_app(self, scope, receive, send)

        middleware = SentryAsgiMiddleware(old_app.__get__(self, cls))._run_asgi3
        return await middleware(scope, receive, send)

    cls.__call__ = sentry_patched_asgi_handler


def patch_channels_asgi_handler_impl(cls):
    # type: (Any) -> None
    old_app = cls.__call__

    async def sentry_patched_asgi_handler(self, receive, send):
        # type: (Any, Any, Any) -> Any
        if Hub.current.get_integration(DjangoIntegration) is None:
            return await old_app(self, receive, send)

        middleware = SentryAsgiMiddleware(lambda _scope: old_app.__get__(self, cls))

        return await middleware(self.scope)(receive, send)

    cls.__call__ = sentry_patched_asgi_handler