Ordered http request parameters

2019-07-19 02:52发布

问题:

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