Skip to content

Commit

Permalink
fix(django): Don't let RawPostDataException bubble up (#3553)
Browse files Browse the repository at this point in the history
  • Loading branch information
sentrivana committed Sep 23, 2024
1 parent ed614c0 commit 0ee7c50
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
8 changes: 7 additions & 1 deletion sentry_sdk/integrations/_wsgi_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,13 @@ def json(self):
if not self.is_json():
return None

raw_data = self.raw_data()
try:
raw_data = self.raw_data()
except (RawPostDataException, ValueError):
# The body might have already been read, in which case this will
# fail
raw_data = None

if raw_data is None:
return None

Expand Down
28 changes: 27 additions & 1 deletion tests/integrations/django/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
import re
import pytest
from functools import partial
from unittest.mock import patch

from werkzeug.test import Client

from django import VERSION as DJANGO_VERSION
from django.contrib.auth.models import User
from django.core.management import execute_from_command_line
from django.db.utils import OperationalError, ProgrammingError, DataError
from django.http.request import RawPostDataException

try:
from django.urls import reverse
Expand All @@ -20,7 +22,11 @@
from sentry_sdk._compat import PY310
from sentry_sdk import capture_message, capture_exception
from sentry_sdk.consts import SPANDATA
from sentry_sdk.integrations.django import DjangoIntegration, _set_db_data
from sentry_sdk.integrations.django import (
DjangoIntegration,
DjangoRequestExtractor,
_set_db_data,
)
from sentry_sdk.integrations.django.signals_handlers import _get_receiver_name
from sentry_sdk.integrations.executing import ExecutingIntegration
from sentry_sdk.tracing import Span
Expand Down Expand Up @@ -740,6 +746,26 @@ def test_read_request(sentry_init, client, capture_events):
assert "data" not in event["request"]


def test_request_body_already_read(sentry_init, client, capture_events):
sentry_init(integrations=[DjangoIntegration()])

events = capture_events()

class MockExtractor(DjangoRequestExtractor):
def raw_data(self):
raise RawPostDataException

with patch("sentry_sdk.integrations.django.DjangoRequestExtractor", MockExtractor):
client.post(
reverse("post_echo"), data=b'{"hey": 42}', content_type="application/json"
)

(event,) = events

assert event["message"] == "hi"
assert "data" not in event["request"]


def test_template_tracing_meta(sentry_init, client, capture_events):
sentry_init(integrations=[DjangoIntegration()])
events = capture_events()
Expand Down

0 comments on commit 0ee7c50

Please sign in to comment.