具有受控的HTTP头排序的Python HTTP请求 [英] Python HTTP request with controlled ordering of HTTP headers
问题描述
我正在使用python编写一个客户端接口到一个安静的Web服务,不幸的是,Web服务需要在请求中出现自定义头文件。我一直在使用请求,但Web服务还要求标头在请求中按特定顺序排列。我无法弄清楚请求如何命令标题,看看是否有办法控制这种排序。
I am programming a client interface to a restful web service in python and unfortunately the web service requires custom headers to be present in the request. I have been using Requests for this however the web service also requires the headers to be in a specific order in the request. I haven't been able to figure out how Requests orders the headers and see if there is a way to be able to control this ordering.
我也愿意使用如果有人有推荐,我的申请中除了请求之外的另一个模块。
I am also open to using another module other than Requests in my application if someone has a recommendation.
推荐答案
更新回答
以下答案涉及2.9.2以下的版本。从版本2.9.2(2016年4月左右)开始,使用 OrderedDict
再次工作。
看起来有些可能之前使用内置功能( issue 179 )。我认为现在已经没有了( issue 2057 ),其中一个原因在于另一条评论是 num1 。我使用了以下解决方案/解决方法。
It looks like it was possible some time ago using just the built-in functionality (issue 179). I think it is not anymore (issue 2057) and one of the reasons is mentioned in another comment by num1. I have used a following solution/workaround.
import requests
import collections
class SortedHTTPAdapter(requests.adapters.HTTPAdapter):
def add_headers(self, request, **kwargs):
request.headers = collections.OrderedDict(
((key, value) for key, value in sorted(request.headers.items()))
)
session = requests.Session()
session.mount("http://", SortedHTTPAdapter())
在示例标题中只是排序但是可以对它们进行排序以任何方式。我在通过 requests
代码并阅读方法的文档字符串后选择了该方法:
In the example headers are just sorted but one can order them in any way. I chose that method after going through requests
code and reading the method's docstring:
添加连接所需的任何标头。从v2.0开始,默认情况下这不会产生任何
,而是留给子类
HTTPAdapter< requests.adapters.HTTPAdapter>
class。
对于绝对控制,可能会覆盖发送
方法。
For absolute control one could override the send
method probably.
这篇关于具有受控的HTTP头排序的Python HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!