Python 如何获取 Django 中的所有请求标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3889769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get all the request headers in Django?
提问by Mridang Agarwalla
I need to get all the Django request headers. From what i've read, Django simply dumps everything into the request.METAvariable along with a lot aof other data. What would be the best way to get allthe headers that the client sent to my Django application?
我需要获取所有 Django 请求标头。从我读过的内容来看,Django 只是将所有内容request.META连同许多其他数据一起转储到变量中。获取客户端发送到我的 Django 应用程序的所有标头的最佳方法是什么?
I'm going use these to build a httplibrequest.
我将使用这些来构建httplib请求。
采纳答案by Manoj Govindan
According to the documentationrequest.METAis a "standard Python dictionary containing all available HTTP headers". If you want to get allthe headers you can simply iterate through the dictionary.
根据文档request.META是“包含所有可用 HTTP 标头的标准 Python 字典”。如果你想获得所有的标题,你可以简单地遍历字典。
Which part of your code to do this depends on your exact requirement. Anyplace that has access to requestshould do.
执行此操作的代码的哪一部分取决于您的确切要求。任何可以访问的地方都request应该这样做。
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.
我需要在中间件类中访问它,但是当我对其进行迭代时,除了 HTTP 标头之外,我还得到了很多值。
From the documentation:
从文档:
With the exception of
CONTENT_LENGTHandCONTENT_TYPE, as given above, anyHTTPheaders in the request are converted toMETAkeys by converting all characters to uppercase, replacing any hyphens with underscores and adding anHTTP_prefix to the name.
除了上面给出的
CONTENT_LENGTHandCONTENT_TYPE之外,通过将所有字符转换为大写,将所有连字符替换为下划线并在 name 中添加前缀,HTTP请求中的任何标头都会转换为META键。HTTP_
(Emphasis added)
(强调)
To get the HTTPheaders alone, just filter by keys prefixed with HTTP_.
要HTTP单独获取标题,只需按前缀为HTTP_.
Update 2
更新 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.
你能告诉我如何通过从 request.META 变量中过滤掉所有以 HTTP_ 开头的键并去掉领先的 HTTP_ 部分来构建标题字典。
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_'))
回答by Srikanth Chundi
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.
我认为没有任何简单的方法可以只获取 HTTP 标头。您必须遍历 request.META dict 才能获得所需的一切。
django-debug-toolbar takes the same approach to show header information. Have a look at this fileresponsible for retrieving header information.
回答by Dave Gallagher
This is another way to do it, very similar to Manoj Govindan's answer above:
这是另一种方法,与上面Manoj Govindan的回答非常相似:
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_TYPEand CONTENT_LENGTHrequest headers, along with the HTTP_ones. request_headers['some_key]== request.META['some_key'].
这也将抓取CONTENT_TYPE和CONTENT_LENGTH请求标头以及HTTP_那些标头。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 在这里列出了一堆,但不是全部:https: //docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META
Django's algorithm for request headers:
Django 的请求头算法:
- Replace hyphen
-with underscore_ - Convert to UPPERCASE.
- Prepend
HTTP_to all headers in original request, except forCONTENT_TYPEandCONTENT_LENGTH.
-用下划线替换连字符_- 转换为大写。
- 附加
HTTP_到原始请求中的所有标头,除了CONTENT_TYPE和CONTENT_LENGTH。
The values of each header should be unmodified.
每个标头的值应该是未修改的。
回答by abhayAndPoorvisDad
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-revproxythat accomplishes exactly this.
就其价值而言,您的意图似乎是使用传入的 HTTP 请求来形成另一个 HTTP 请求。有点像网关。有一个出色的模块django-revproxy可以完成此任务。
The source is a pretty good reference on how to accomplish what you are trying to do.
来源是关于如何完成您正在尝试做的事情的很好的参考。
回答by S. Nick
<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
<code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}
回答by James Vare Samuel
request.META.get('HTTP_AUTHORIZATION')
/python3.6/site-packages/rest_framework/authentication.py
request.META.get('HTTP_AUTHORIZATION')
/python3.6/site-packages/rest_framework/authentication.py
you can get that from this file though...
你可以从这个文件中得到它...
回答by Tony Aziz
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)
回答by Daniel Hepper
Starting from Django 2.2, you can use request.headersto access the HTTP headers. From the documentation on HttpRequest.headers:
从 Django 2.2 开始,您可以使用request.headers访问 HTTP 标头。从关于 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)
一个不区分大小写的类似 dict 的对象,它提供对来自请求的所有 HTTP 前缀头(加上 Content-Length 和 Content-Type)的访问。
每个标题的名称在显示时都使用标题大小写(例如 User-Agent)进行样式化。您可以不区分大小写地访问标头:
>>> 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().
要获取所有标题,您可以使用request.headers.keys()或request.headers.items()。
回答by Kushan Gunasekera
Simply you can use HttpRequest.headersfrom Django 2.2onward. Following example is directly taken from the official Django Documentationunder Request and response objectssection.
简单地说,您可以从Django 2.2开始使用HttpRequest.headers。以下示例直接取自请求和响应对象部分下的官方Django 文档。
>>> 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)

