订购的HTTP请求参数 [英] Ordered http request parameters

查看:55
本文介绍了订购的HTTP请求参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向其发出请求的API要求参数按指定顺序排列.最初,我使用了 requests lib

The API to which I need to make request require parameters in specified order. At first I had used requests lib

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)

文档中说.请求未采用显式参数

r = requests.get("http://httpbin.org/get", param1=payload1, param2=payload2)

我直接尝试了urllib3之后,但是返回了上面的错误.错误提示:

After I had tryed urllib3 directly, but it returns me an error as above. From error:

def request_encode_body(self, method, url, fields=None, headers=None,

如何在Python和任何库中以指定顺序设置http请求参数.

How to set http request parameters in specified order in Python, any libs.

推荐答案

请改用一系列二值元组:

Use a sequence of two-value tuples instead:

payload = (('key1', 'value1'), ('key2', 'value2'))
r = requests.get("http://httpbin.org/get", params=payload)

使用字典时 requests 不保留排序的原因是因为python字典没有排序.另一方面,元组或列表可以,因此可以保留顺序.

The reason requests doesn't retain ordering when using a dictionary is because python dictionaries do not have ordering. A tuple or a list, on the other hand, does, so the ordering can be retained.

演示:

>>> payload = (('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'))
>>> r = requests.get("http://httpbin.org/get", params=payload)
>>> print r.json
{u'url': u'http://httpbin.org/get?key1=value1&key2=value2&key3=value3', u'headers': {u'Content-Length': u'', u'Accept-Encoding': u'gzip, deflate, compress', u'Connection': u'keep-alive', u'Accept': u'*/*', u'User-Agent': u'python-requests/0.14.1 CPython/2.7.3 Darwin/11.4.2', u'Host': u'httpbin.org', u'Content-Type': u''}, u'args': {u'key3': u'value3', u'key2': u'value2', u'key1': u'value1'}, u'origin': u'109.247.40.35'}

这篇关于订购的HTTP请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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