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

#2114 repeating query in django view #2158

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions elasticapm/utils/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import uuid
from decimal import Decimal

from django.db.models import QuerySet
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
from django.db.models import QuerySet
try:
from django.db.models import QuerySet as DjangoQuerySet
except ImportError:
DjangoQuerySet = None

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point i will change it 👌

from elasticapm.conf.constants import KEYWORD_MAX_LENGTH, LABEL_RE, LABEL_TYPES, LONG_FIELD_MAX_LENGTH

PROTECTED_TYPES = (int, type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time)
Expand Down Expand Up @@ -144,6 +145,9 @@ class value_type(list):
ret = float(value)
elif isinstance(value, int):
ret = int(value)
elif isinstance(value, QuerySet):
value._result_cache = []
ret = repr(value)
Copy link
Member

@xrmx xrmx Dec 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
elif isinstance(value, QuerySet):
value._result_cache = []
ret = repr(value)
elif DjangoQuerySet is not None and isinstance(value, DjangoQuerySet) and getattr(value, "_result_cache", True) is None:
# if we have a Django QuerySet a None result cache it may mean that the underlying query failed
# so represent it as an empty list instead of retrying the query again
ret = "<%s %r>" % (value.__class__.__name__, [])

Instead of erasing the values everytime shouldn't we just do something is value._result_cache is None?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, there is a little less magic to your solution 👌

elif value is not None:
try:
ret = transform(repr(value))
Expand Down
15 changes: 15 additions & 0 deletions tests/contrib/django/django_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1318,6 +1318,21 @@ def test_capture_post_errors_dict(client, django_elasticapm_client):
assert error["context"]["request"]["body"] == "[REDACTED]"


@pytest.mark.parametrize(
"django_sending_elasticapm_client",
[{"capture_body": "errors"}, {"capture_body": "transactions"}, {"capture_body": "all"}, {"capture_body": "off"}],
indirect=True,
)
def test_capture_django_orm_timeout_error(client, django_sending_elasticapm_client):
with pytest.raises(DatabaseError):
client.get(reverse("elasticapm-django-orm-exc"))

errors = django_sending_elasticapm_client.httpserver.payloads
if django_sending_elasticapm_client.config.capture_body in (constants.ERROR, "all"):
stacktrace = errors[0][1]["error"]["exception"]["stacktrace"]
assert "'qs': '[]'" in str(stacktrace)


def test_capture_body_config_is_dynamic_for_errors(client, django_elasticapm_client):
django_elasticapm_client.config.update(version="1", capture_body="all")
with pytest.raises(MyException):
Expand Down
1 change: 1 addition & 0 deletions tests/contrib/django/testapp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def handler500(request):
re_path(r"^trigger-500-ioerror$", views.raise_ioerror, name="elasticapm-raise-ioerror"),
re_path(r"^trigger-500-decorated$", views.decorated_raise_exc, name="elasticapm-raise-exc-decor"),
re_path(r"^trigger-500-django$", views.django_exc, name="elasticapm-django-exc"),
re_path(r"^trigger-500-django-orm-exc$", views.django_queryset_error, name="elasticapm-django-orm-exc"),
re_path(r"^trigger-500-template$", views.template_exc, name="elasticapm-template-exc"),
re_path(r"^trigger-500-log-request$", views.logging_request_exc, name="elasticapm-log-request-exc"),
re_path(r"^streaming$", views.streaming_view, name="elasticapm-streaming-view"),
Expand Down
14 changes: 14 additions & 0 deletions tests/contrib/django/testapp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
from django.http import HttpResponse, StreamingHttpResponse
from django.shortcuts import get_object_or_404, render
from django.views import View
from django.db.models import QuerySet
from django.db import DatabaseError

import elasticapm

Expand Down Expand Up @@ -70,6 +72,18 @@ def django_exc(request):
return get_object_or_404(MyException, pk=1)


def django_queryset_error(request):
"""Simulation of django ORM timeout"""
class CustomQuerySet(QuerySet):
def all(self):
raise DatabaseError()

def __repr__(self) -> str:
return str(self._result_cache)

qs = CustomQuerySet()
list(qs.all())

def raise_exc(request):
raise MyException(request.GET.get("message", "view exception"))

Expand Down