Skip to content

Commit

Permalink
fix: django content length extraction bug (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-sanche committed Jan 27, 2021
1 parent b7fd0ed commit 93eeaef
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
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

0 comments on commit 93eeaef

Please sign in to comment.