I need to get all the Django request headers. From what i've read, Django simply dumps everything into the request.META
variable along with a lot aof other data. What would be the best way to get all the headers that the client sent to my Django application?
I'm going use these to build a httplib
request.
I don't think there is any easy way to get only HTTP headers. You have to iterate through request.META dict to get what all you need.
django-debug-toolbar takes the same approach to show header information. Have a look at this file responsible for retrieving header information.
This is another way to do it, very similar to Manoj Govindan's answer above:
That will also grab the
CONTENT_TYPE
andCONTENT_LENGTH
request headers, along with theHTTP_
ones.request_headers['some_key]
==request.META['some_key']
.Modify accordingly if you need to include/omit certain headers. Django lists a bunch, but not all, of them here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META
Django's algorithm for request headers:
-
with underscore_
HTTP_
to all headers in original request, except forCONTENT_TYPE
andCONTENT_LENGTH
.The values of each header should be unmodified.
For what it's worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.
The source is a pretty good reference on how to accomplish what you are trying to do.
request.META.get('HTTP_AUTHORIZATION')
/python3.6/site-packages/rest_framework/authentication.py
you can get that from this file though...
According to the documentation
request.META
is a "standard Python dictionary containing all available HTTP headers". If you want to get all the headers you can simply iterate through the dictionary.Which part of your code to do this depends on your exact requirement. Anyplace that has access to
request
should do.Update
From the documentation:
(Emphasis added)
To get the
HTTP
headers alone, just filter by keys prefixed withHTTP_
.Update 2
Sure. Here is one way to do it.