Skip to content

Commit 0ee7c50

Browse files
authored
fix(django): Don't let RawPostDataException bubble up (getsentry#3553)
1 parent ed614c0 commit 0ee7c50

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

sentry_sdk/integrations/_wsgi_common.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,13 @@ def json(self):
152152
if not self.is_json():
153153
return None
154154

155-
raw_data = self.raw_data()
155+
try:
156+
raw_data = self.raw_data()
157+
except (RawPostDataException, ValueError):
158+
# The body might have already been read, in which case this will
159+
# fail
160+
raw_data = None
161+
156162
if raw_data is None:
157163
return None
158164

tests/integrations/django/test_basic.py

+27-1
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
import re
44
import pytest
55
from functools import partial
6+
from unittest.mock import patch
67

78
from werkzeug.test import Client
89

910
from django import VERSION as DJANGO_VERSION
1011
from django.contrib.auth.models import User
1112
from django.core.management import execute_from_command_line
1213
from django.db.utils import OperationalError, ProgrammingError, DataError
14+
from django.http.request import RawPostDataException
1315

1416
try:
1517
from django.urls import reverse
@@ -20,7 +22,11 @@
2022
from sentry_sdk._compat import PY310
2123
from sentry_sdk import capture_message, capture_exception
2224
from sentry_sdk.consts import SPANDATA
23-
from sentry_sdk.integrations.django import DjangoIntegration, _set_db_data
25+
from sentry_sdk.integrations.django import (
26+
DjangoIntegration,
27+
DjangoRequestExtractor,
28+
_set_db_data,
29+
)
2430
from sentry_sdk.integrations.django.signals_handlers import _get_receiver_name
2531
from sentry_sdk.integrations.executing import ExecutingIntegration
2632
from sentry_sdk.tracing import Span
@@ -740,6 +746,26 @@ def test_read_request(sentry_init, client, capture_events):
740746
assert "data" not in event["request"]
741747

742748

749+
def test_request_body_already_read(sentry_init, client, capture_events):
750+
sentry_init(integrations=[DjangoIntegration()])
751+
752+
events = capture_events()
753+
754+
class MockExtractor(DjangoRequestExtractor):
755+
def raw_data(self):
756+
raise RawPostDataException
757+
758+
with patch("sentry_sdk.integrations.django.DjangoRequestExtractor", MockExtractor):
759+
client.post(
760+
reverse("post_echo"), data=b'{"hey": 42}', content_type="application/json"
761+
)
762+
763+
(event,) = events
764+
765+
assert event["message"] == "hi"
766+
assert "data" not in event["request"]
767+
768+
743769
def test_template_tracing_meta(sentry_init, client, capture_events):
744770
sentry_init(integrations=[DjangoIntegration()])
745771
events = capture_events()

0 commit comments

Comments
 (0)