Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 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
41 changes: 39 additions & 2 deletions sentry_sdk/integrations/django/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from typing import Optional
from typing import Iterator
from typing import Tuple
from typing import Union

try:
# support Django 1.9
Expand Down Expand Up @@ -57,6 +58,38 @@ def _get_template_name_description(template_name):
return template_name


def _normalize_context(context):
# type: (Dict[str, Any]) -> Dict[str, Union[str, int, float, bool, None, list[Union[str, int, float, bool, None]], dict[str, Union[str, int, float, bool, None]]]]
"""
Filter out non-primitive types from `context`.
"""
new_context = (
{}
) # type: Dict[str, Union[str, int, float, bool, None, list[Union[str, int, float, bool, None]], dict[str, Union[str, int, float, bool, None]]]]
for key, value in context.items():
if isinstance(value, (str, int, float, bool, type(None))):
new_context[key] = value
continue

if isinstance(value, list):
new_context[key] = [
item
for item in value
if isinstance(item, (str, int, float, bool, type(None)))
]
continue

if isinstance(value, dict):
new_context[key] = {
k: v
for k, v in value.items()
if isinstance(v, (str, int, float, bool, type(None)))
}
continue

return new_context


def patch_templates():
# type: () -> None
from django.template.response import SimpleTemplateResponse
Expand All @@ -73,7 +106,9 @@ def rendered_content(self):
name=_get_template_name_description(self.template_name),
origin=DjangoIntegration.origin,
) as span:
span.set_data("context", self.context_data)
new_context = _normalize_context(self.context_data)
span.set_data("context", new_context)

return real_rendered_content.fget(self)

SimpleTemplateResponse.rendered_content = rendered_content
Expand Down Expand Up @@ -101,7 +136,9 @@ def render(request, template_name, context=None, *args, **kwargs):
name=_get_template_name_description(template_name),
origin=DjangoIntegration.origin,
) as span:
span.set_data("context", context)
new_context = _normalize_context(context)
span.set_data("context", new_context)

return real_render(request, template_name, context, *args, **kwargs)

django.shortcuts.render = render
Expand Down
1 change: 1 addition & 0 deletions tests/integrations/django/myapp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def path(path, *args, **kwargs):
path("template-test", views.template_test, name="template_test"),
path("template-test2", views.template_test2, name="template_test2"),
path("template-test3", views.template_test3, name="template_test3"),
path("template-test4", views.template_test4, name="template_test4"),
path("postgres-select", views.postgres_select, name="postgres_select"),
path("postgres-select-slow", views.postgres_select_orm, name="postgres_select_orm"),
path(
Expand Down
21 changes: 21 additions & 0 deletions tests/integrations/django/myapp/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import json
import threading
import time

from django.contrib.auth import login
from django.contrib.auth.models import User
Expand Down Expand Up @@ -208,6 +209,26 @@ def template_test3(request, *args, **kwargs):
return render(request, "trace_meta.html", {})


@csrf_exempt
def template_test4(request, *args, **kwargs):
template_context = {
"user_age": 25,
"complex_context": lambda x: time.sleep(10),
"complex_list": [1, 2, 3, lambda x: time.sleep(10)],
"complex_dict": {
"a": 1,
"d": lambda x: time.sleep(10),
},
"none_context": None,
}

return TemplateResponse(
request,
"user_name.html",
template_context,
)


@csrf_exempt
def postgres_select(request, *args, **kwargs):
from django.db import connections
Expand Down
40 changes: 38 additions & 2 deletions tests/integrations/django/test_basic.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import inspect
import json
import os
import pytest
import re
import sys
import pytest
import time
from functools import partial
from unittest.mock import patch

Expand All @@ -15,8 +16,8 @@
from django.core.management import execute_from_command_line
from django.db.utils import OperationalError, ProgrammingError, DataError
from django.http.request import RawPostDataException
from django.utils.functional import SimpleLazyObject
from django.template.context import make_context
from django.utils.functional import SimpleLazyObject

try:
from django.urls import reverse
Expand Down Expand Up @@ -956,6 +957,41 @@ def test_render_spans(sentry_init, client, capture_events, render_span_tree):
assert expected_line in render_span_tree(transaction)


@pytest.mark.skipif(DJANGO_VERSION < (1, 9), reason="Requires Django >= 1.9")
def test_render_spans_complex_context(sentry_init, client, capture_events):
sentry_init(
integrations=[
DjangoIntegration(
cache_spans=False,
middleware_spans=False,
signals_spans=False,
)
],
traces_sample_rate=1.0,
)
events = capture_events()

begin = time.time()
client.get(reverse("template_test4"))

(transaction,) = events
end = time.time()

# evaluating the complex context takes 10 seconds, (see lambda in template_test4)
# so we expect the total time to be way less, because the complex context is not evaluated
assert end - begin < 10 / 5

# Make sure complex items are not put into the span.data
assert transaction["spans"][-1]["data"]["context"] == {
"user_age": 25,
"complex_dict": {
"a": 1,
},
"complex_list": [1, 2, 3],
"none_context": None,
}


if DJANGO_VERSION >= (1, 10):
EXPECTED_MIDDLEWARE_SPANS = """\
- op="http.server": description=null
Expand Down