Ordered http request parameters

烂漫一生 提交于 2019-12-24 04:00:15

问题


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)

Like is says in documents. requests does not take parameters explicit

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

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,

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


回答1:


Use a sequence of two-value tuples instead:

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

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.

Demo:

>>> 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'}


来源:https://stackoverflow.com/questions/13352185/ordered-http-request-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!