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 dat
<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
<code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}
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.
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.
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
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
andCONTENT_TYPE
, as given above, anyHTTP
headers in the request are converted toMETA
keys by converting all characters to uppercase, replacing any hyphens with underscores and adding anHTTP_
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_'))
If you want to get client key from request header, u can try following:
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from apps.authentication.models import CerebroAuth
class CerebroAuthentication(BaseAuthentication):
def authenticate(self, request):
client_id = request.META.get('HTTP_AUTHORIZATION')
if not client_id:
raise exceptions.AuthenticationFailed('Client key not provided')
client_id = client_id.split()
if len(client_id) == 1 or len(client_id) > 2:
msg = ('Invalid secrer key header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
try:
client = CerebroAuth.objects.get(client_id=client_id[1])
except CerebroAuth.DoesNotExist:
raise exceptions.AuthenticationFailed('No such client')
return (client, None)