Skip to content

Commit 2bf2b81

Browse files
committed
Add function to pretty print HttpRequest
Make it easy to dump the contents of a view's HttpRequest to a logger.
1 parent 1a69675 commit 2bf2b81

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

python/nav/django/utils.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
"""Utility methods for django used in NAV"""
1919

2020
from django.core.exceptions import FieldDoesNotExist
21+
from django.http import HttpRequest
2122
from django.urls import reverse
2223
from django.utils.http import urlencode
2324

@@ -56,6 +57,39 @@ def get_verbose_name(model, lookup):
5657
raise FieldDoesNotExist
5758

5859

60+
def pp_request(request: HttpRequest, function, *attributes) -> None:
61+
"""View ``request`` via `function``, one line per attribute
62+
63+
Use the ``attributes`` parameter to limit what attributes are inspected.
64+
65+
Also dumps the contents of the dicts ``request.environ``and
66+
``request.META``, one line per value, sorted per key.
67+
68+
The ``function`` must have an input signature compatible with
69+
``logging.Logger.debug()``.
70+
71+
Meant for debugging via logs.
72+
73+
Example usage::
74+
75+
pp_request(request, logging.getLogger(__name__).debug)
76+
"""
77+
DICT_ATTRIBUTES = ('META', 'environ')
78+
79+
existing_attributes = vars(request).keys()
80+
if attributes:
81+
attributes = set(existing_attributes).intersection(attributes)
82+
else:
83+
attributes = existing_attributes
84+
for attribute in sorted(attributes):
85+
value = getattr(request, attribute)
86+
if attribute in DICT_ATTRIBUTES:
87+
for key in sorted(value.keys()):
88+
function('request.%s: %s: %s', attribute, key, value[key])
89+
else:
90+
function('request.%s: %s', attribute, value)
91+
92+
5993
#
6094
# Django version differentiated helper functions:
6195
#

0 commit comments

Comments
 (0)