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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: django content length extraction bug #160

Merged
merged 3 commits into from Jan 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion google/cloud/logging_v2/handlers/_helpers.py
Expand Up @@ -24,6 +24,7 @@

from google.cloud.logging_v2.handlers.middleware.request import _get_django_request

_DJANGO_CONTENT_LENGTH = "CONTENT_LENGTH"
_DJANGO_TRACE_HEADER = "HTTP_X_CLOUD_TRACE_CONTEXT"
_DJANGO_USERAGENT_HEADER = "HTTP_USER_AGENT"
_DJANGO_REMOTE_ADDR_HEADER = "REMOTE_ADDR"
Expand Down Expand Up @@ -93,11 +94,18 @@ def get_request_data_from_django():

if request is None:
return None, None

# convert content_length to int if it exists
content_length = None
try:
content_length = int(request.META.get(_DJANGO_CONTENT_LENGTH))
except (ValueError, TypeError):
content_length = None
# build http_request
http_request = {
"requestMethod": request.method,
"requestUrl": request.build_absolute_uri(),
"requestSize": len(request.body),
"requestSize": content_length,
"userAgent": request.META.get(_DJANGO_USERAGENT_HEADER),
"remoteIp": request.META.get(_DJANGO_REMOTE_ADDR_HEADER),
"referer": request.META.get(_DJANGO_REFERER_HEADER),
Expand Down
3 changes: 3 additions & 0 deletions tests/unit/handlers/test__helpers.py
Expand Up @@ -172,6 +172,9 @@ def test_http_request_populated(self):
HTTP_USER_AGENT=expected_agent,
HTTP_REFERER=expected_referrer,
)
# ensure test passes even after request has been read
# context: https://github.com/googleapis/python-logging/issues/159
django_request.read()

middleware = request.RequestMiddleware(None)
middleware.process_request(django_request)
Expand Down