有序请求参数python

时间:2013-10-13 16:05:59

标签: python post python-3.x params python-requests

如何在请求中发布有序的参数?

我尝试了以下方法,但没有一个有效:

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')])

我得到的错误是:

SyntaxError: invalid syntax

这一个帖子参数按随机顺序没有错误:

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

如何使用以下代码发布有序参数?

c = requests.post(url, params = payload)

1 个答案:

答案 0 :(得分:4)

  • dict{...}错了,它应该是dict(...)OrderedDict{...}
  • 也是如此
  • dictOrderedDict将序列作为参数
  • 您的元组列表中包含('e':8,'data[1]','9')。应该是('e',8),('data[1]','9')

这会产生 dict (它相当于您发布的工作字典文字),总是无序

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')])

这会产生一个元组元组请求不会作为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'))

其余两个(有序词典元组列表)将产生您想要的内容:

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')]