|
18 | 18 | """Utility methods for django used in NAV""" |
19 | 19 |
|
20 | 20 | from django.core.exceptions import FieldDoesNotExist |
| 21 | +from django.http import HttpRequest |
21 | 22 | from django.urls import reverse |
22 | 23 | from django.utils.http import urlencode |
23 | 24 |
|
@@ -56,6 +57,39 @@ def get_verbose_name(model, lookup): |
56 | 57 | raise FieldDoesNotExist |
57 | 58 |
|
58 | 59 |
|
| 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 | + |
59 | 93 | # |
60 | 94 | # Django version differentiated helper functions: |
61 | 95 | # |
|
0 commit comments