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

查看:33
本文介绍了如何获取 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.

推荐答案

根据 documentation request.META 是包含所有可用 HTTP 标头的标准 Python 字典".如果您想获得 all 标题,您可以简单地遍历字典.

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.

执行此操作的代码的哪一部分取决于您的确切要求.任何可以访问 request 的地方都应该这样做.

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_LENGTHCONTENT_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.

当然.这是一种方法.

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天全站免登陆