Skip to content

Commit b39a68d

Browse files
authored
fix: Capture WSGI variables early (#223)
* fix: Capture WSGI variables early * doc: Explain reasoning behind change
1 parent 2ca868c commit b39a68d

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

sentry_sdk/integrations/wsgi.py

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,25 @@ def close(self):
163163

164164

165165
def _make_wsgi_event_processor(environ):
166+
# It's a bit unfortunate that we have to extract and parse the request data
167+
# from the environ so eagerly, but there are a few good reasons for this.
168+
#
169+
# We might be in a situation where the scope/hub never gets torn down
170+
# properly. In that case we will have an unnecessary strong reference to
171+
# all objects in the environ (some of which may take a lot of memory) when
172+
# we're really just interested in a few of them.
173+
#
174+
# Keeping the environment around for longer than the request lifecycle is
175+
# also not necessarily something uWSGI can deal with:
176+
# https://github.com/unbit/uwsgi/issues/1950
177+
178+
client_ip = get_client_ip(environ)
179+
request_url = get_request_url(environ)
180+
query_string = environ.get("QUERY_STRING")
181+
method = environ.get("REQUEST_METHOD")
182+
env = dict(_get_environ(environ))
183+
headers = _filter_headers(dict(_get_headers(environ)))
184+
166185
def event_processor(event, hint):
167186
with capture_internal_exceptions():
168187
# if the code below fails halfway through we at least have some data
@@ -171,22 +190,13 @@ def event_processor(event, hint):
171190
if _should_send_default_pii():
172191
user_info = event.setdefault("user", {})
173192
if "ip_address" not in user_info:
174-
user_info["ip_address"] = get_client_ip(environ)
175-
176-
if "url" not in request_info:
177-
request_info["url"] = get_request_url(environ)
178-
179-
if "query_string" not in request_info:
180-
request_info["query_string"] = environ.get("QUERY_STRING")
181-
182-
if "method" not in request_info:
183-
request_info["method"] = environ.get("REQUEST_METHOD")
184-
185-
if "env" not in request_info:
186-
request_info["env"] = dict(_get_environ(environ))
193+
user_info.setdefault("ip_address", client_ip)
187194

188-
if "headers" not in request_info:
189-
request_info["headers"] = _filter_headers(dict(_get_headers(environ)))
195+
request_info.setdefault("url", request_url)
196+
request_info.setdefault("query_string", query_string)
197+
request_info.setdefault("method", method)
198+
request_info.setdefault("env", env)
199+
request_info.setdefault("headers", headers)
190200

191201
return event
192202

0 commit comments

Comments
 (0)