Question

How can I post ordered params in requests?

I have tried the following, but none of them work:

payload = dict{('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e':8,'data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15')}

payload = OrderedDict{('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e':8,'data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15')}

payload = (('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e':8,'data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15'))

payload = ([('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e':8,'data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15')])

The error I am getting is:

SyntaxError: invalid syntax

This one post parameters in random order without an error:

payload = {'f':'1','s':'2','t':'3','f':'4','ft':'5','s':'6','se':'7','e':8,'data[1]':'9','t':'10','el':'1q','data[2]':'12','data[3]':'13','data[4]':'14','htmldata[5]':'15'}

How can I post ordered params using the following code?

c = requests.post(url, params = payload)
Was it helpful?

Solution

  • dict{...} is wrong, it should be dict(...). Same goes for OrderedDict{...}
  • dict and OrderedDict take a sequence as argument
  • you have ('e':8,'data[1]','9') within your list of tuples. Should probably be ('e',8),('data[1]','9').

This produces a dict (it's equivalent to the working dict literal you posted), which will always be unordered:

payload = dict([('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e', 8),('data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15')])

This produces a tuple of tuples, which requests doesn't take as argument for data:

payload = (('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e', 8),('data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15'))

The remaining two (ordered dictionary and list of tuples) will produce what you want:

from collections import OrderedDict
payload = OrderedDict([('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e',8),('data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15')])
payload = [('f','1'),('s','2'),('t','3'),('f','4'),('ft','5'),('s','6'),('se','7'),('e', 8),('data[1]','9'),('t','10'),('el','1q'),('data[2]','12'),('data[3]','13'),('data[4]','14'),('htmldata[5]','15')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top