open-telemetry / opentelemetry-python-contrib

OpenTelemetry instrumentation for Python modules
https://opentelemetry.io
Apache License 2.0
733 stars 606 forks source link

Django instrumentation assumes ASGI is only for Django3+ #1416

Open pilhuhn opened 2 years ago

pilhuhn commented 2 years ago

Describe your environment

My code is on Django 2.x. And I run into https://github.com/open-telemetry/opentelemetry-python/issues/2833 Debugging down shows that the _is_asgi_request() in otel_middleware.py is thus determining that a request can't be an ASGI request.

Steps to reproduce

Just look at the code. Also when you continue and set is_asgi_request to True manually, my code works as expected

What is the expected behavior?

Just use ASGi and don't run into #2833

What is the actual behavior?

Run into #2833 as even valid ASGi requests are treated like WSGi ones, which then fails.

pilhuhn commented 2 years ago

A fix in my case, as we use the channels.http library / channels package would be:

if DJANGO_3_0:
    from django.core.handlers.asgi import ASGIRequest
else:
    try:
        from channels.http import AsgiRequest
        ASGIRequest = AsgiRequest
    except ImportError:
        ASGIRequest = None