Skip to content

Instantly share code, notes, and snippets.

@aapris
Last active March 5, 2019 13:20
Show Gist options
  • Save aapris/3c10e3792a6f9913a48322e5d86cf484 to your computer and use it in GitHub Desktop.
Save aapris/3c10e3792a6f9913a48322e5d86cf484 to your computer and use it in GitHub Desktop.
Serialize Django>=2.2 HttpRequest
"""
Sometimes you need to pass forward HttpRequest, which is not directly serializable.
serialize_django_request() takes Django HttpRequest as an argument, extracts
HttpRequest.headers (available since Django 2.2), HttpRequest.body and most interesting
values out from HttpRequest.META and returns them in a dict which is json, msgpack etc.
serializable.
"""
from django.http.request import HttpRequest
META_STARTSWITH = ('SERVER', 'REMOTE') # REMOTE_ADDR etc.
META_EXACT = ('QUERY_STRING', 'REQUEST_METHOD', 'SCRIPT_NAME', 'PATH_INFO')
def serialize_django_request(request):
request_meta = {}
mkeys = list(request.META.keys())
mkeys.sort()
for k in mkeys:
if k.startswith(META_STARTSWITH) or k in META_EXACT:
request_meta[k] = request.META[k]
request_meta['path'] = request.META['SCRIPT_NAME'] + request.META['PATH_INFO']
return {
'request.headers': dict(request.headers),
'request.META': request_meta,
'request.body': request.body,
'request.GET': dict(request.GET),
'request.POST': dict(request.POST),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment