173👍
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_'))
65👍
Starting from Django 2.2, you can use request.headers
to access the HTTP headers. From the documentation on HttpRequest.headers:
A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type) from the request.
The name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. You can access headers case-insensitively:
>>> request.headers {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...} >>> 'User-Agent' in request.headers True >>> 'user-agent' in request.headers True >>> request.headers['User-Agent'] Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) >>> request.headers['user-agent'] Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) >>> request.headers.get('User-Agent') Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) >>> request.headers.get('user-agent') Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
To get all headers, you can use request.headers.keys()
or request.headers.items()
.
- [Django]-Separating form input and model validation in Django?
- [Django]-How to add a cancel button to DeleteView in django
- [Django]-Switching to PostgreSQL fails loading datadump
19👍
This is another way to do it, very similar to Manoj Govindan‘s answer above:
import re
regex_http_ = re.compile(r'^HTTP_.+$')
regex_content_type = re.compile(r'^CONTENT_TYPE$')
regex_content_length = re.compile(r'^CONTENT_LENGTH$')
request_headers = {}
for header in request.META:
if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header):
request_headers[header] = request.META[header]
That will also grab the CONTENT_TYPE
and CONTENT_LENGTH
request headers, along with the HTTP_
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:
- Replace hyphen
-
with underscore_
- Convert to UPPERCASE.
- Prepend
HTTP_
to all headers in original request, except forCONTENT_TYPE
andCONTENT_LENGTH
.
The values of each header should be unmodified.
- [Django]-Python Django Gmail SMTP setup
- [Django]-Django: How can I create a multiple select form?
- [Django]-Django composite unique on multiple model fields
19👍
Simply you can use HttpRequest.headers from Django 2.2 onward. Following example is directly taken from the official Django Documentation under Request and response objects section.
>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}
>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True
>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
- [Django]-Update all models at once in Django
- [Django]-How to recursively query in django efficiently?
- [Django]-Django celery task: Newly created model DoesNotExist
7👍
request.META.get(‘HTTP_AUTHORIZATION’)
/python3.6/site-packages/rest_framework/authentication.py
you can get that from this file though…
- [Django]-Specifying limit and offset in Django QuerySet wont work
- [Django]-How to send email via Django?
- [Django]-Get Timezone from City in Python/Django
3👍
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.
- [Django]-Specifying limit and offset in Django QuerySet wont work
- [Django]-Creating a dynamic choice field
- [Django]-What is choice_set in this Django app tutorial?
1👍
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.
- [Django]-How to perform OR condition in django queryset?
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
- [Django]-How to disable admin-style browsable interface of django-rest-framework?
1👍
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)
- [Django]-How to test auto_now_add in django
- [Django]-OperationalError: database is locked
- [Django]-How to pull a random record using Django's ORM?
0👍
<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
<code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}
- [Django]-How can I filter a Django query with a list of values?
- [Django]-Best practices for getting the most testing coverage with Django/Python?
- [Django]-How can I call a custom Django manage.py command directly from a test driver?
0👍
Just be aware to use "-" instead of "_" in header Key
Because if you use "Current_User" in header, you can not get it by
request.headers.get('Current_User') <-- None
user "xxx-xxx" as the key
- [Django]-How do I include related model fields using Django Rest Framework?
- [Django]-What is the most efficient way to store a list in the Django models?
- [Django]-Override existing Django Template Tags