如何获取Django中的所有请求标头? [英] How can I get all the request headers in Django?

查看:281
本文介绍了如何获取Django中的所有请求标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取所有Django请求头。从我读过的内容中,Django只需将所有内容都转载到 request.META 变量中,并附带很多其他数据。获取所有客户端发送给我的Django应用程序的标题的最佳方式是什么?

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?

我将使用这些来构建一个 httplib 请求。

I'm going use these to build a httplib request.

推荐答案

根据文档 request.META 是一个包含所有可用HTTP标头的标准Python字典。如果你想获得所有的标题,你可以简单地遍历字典。

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.

更新


我需要在中间件类中访问它,但是当我重复使用它时,我会从HTTP标头中获得很多值。

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.

从文档中:


CONTENT_LENGTH CONTENT_TYPE ,如上所述,请求中的任何 HTTP 头通过将所有字符转换为大写,将其替换为 META 键,用下划线替换任何连字符, 添加 HTTP _ 前缀到名称

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.

(加重)

要获取 HTTP 头文件,只需按前缀 HTTP _ 的键过滤。

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

更新2


你能不能告诉我通过从request.META变量中筛选掉所有的键,我可以如何构建一个头字典,该变量以HTTP_开头,并排除了前导的HTTP_部分。

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_'))

这篇关于如何获取Django中的所有请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆