views:

42

answers:

2

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.

Thank you.

+1  A: 

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

I need to access it in a Middleware class but when i iterate over it, I get a lot of values apart from HTTP headers.

From the documentation:

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name.

(Emphasis added)

To get the HTTP headers alone, just filter by keys prefixed with HTTP_.

Update 2

could you show me how I could build a dictionary of headers by filtering out all the keys from the request.META variable which begin with a HTTP_ and strip out the leading HTTP_ part.

Sure. Here is one way to do it.

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))
Manoj Govindan
I need to access it in a Middleware class but when i iterate over it, I get a lot of values apart from HTTP headers.
Mridang Agarwalla
@Mridang: updated my answer. See above.
Manoj Govindan
Thanks Manoj. Just out of curiosity - could you show me how I could build a dictionary of headers by filtering out all the keys from the `request.META` variable which begin with a `HTTP_` and strip out the leading `HTTP_` part. Is this possible through lambda functions? (I think they're called lambda functions) I'm asking this because I would probably go on do it the long way by first iterating over them, then checking to see if it begins with a `HTTP_` and then adding it to the new dictionary. Thanks again.
Mridang Agarwalla
@Mridang: see update #2 above.
Manoj Govindan
Thanks again Manoj. I modified it slightly to use `lstrip('HTTP_')` instead of the regex. :)
Mridang Agarwalla
@Mridang: `lstrip`. Of course. My substitute fu is weak today evening.
Manoj Govindan
A: 

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.

Srikanth Chundi