Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate Django middleware to new-style #533

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#543](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/543))
- Require aiopg to be less than 1.3.0
([#560](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/560))
- `opentelemetry-instrumentation-django` Migrated Django middleware to new-style.
([#533](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/533))

### Added
- `opentelemetry-instrumentation-httpx` Add `httpx` instrumentation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from time import time
from typing import Callable

from django import VERSION as django_version
from django.http import HttpRequest, HttpResponse

from opentelemetry.context import attach, detach
Expand All @@ -42,10 +43,31 @@
except ImportError:
from django.urls import Resolver404, resolve

try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
DJANGO_2_0 = django_version >= (2, 0)

if DJANGO_2_0:
# Since Django 2.0, only `settings.MIDDLEWARE` is supported, so new-style
# middlewares can be used.
class MiddlewareMixin:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
self.process_request(request)
response = self.get_response(request)
return self.process_response(request, response)


else:
# Django versions 1.x can use `settings.MIDDLEWARE_CLASSES` and expect
# old-style middlewares, which are created by inheriting from
# `deprecation.MiddlewareMixin` since its creation in Django 1.10 and 1.11,
# or from `object` for older versions.
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object


_logger = getLogger(__name__)
_attributes_by_preference = [
Expand Down