处理HTTP post中的重复键以指定多个值 [英] handling duplicate keys in HTTP post in order to specify multiple values

查看:607
本文介绍了处理HTTP post中的重复键以指定多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • python 2.7

  • 请求模块

  • 带有重复键的http帖子以指定多个值

Trevor正在使用带有重复键的网站的python请求来指定多个值。问题是,JSON和Python词典不允许重复键,因此只有其中一个键可以通过。

Trevor is using python requests with a website that takes duplicate keys to specify multiple values. The problem is, JSON and Python dictionaries do not allow duplicate keys, so only one of the keys makes it through.


  • 目标是使用python请求创建一个HTTP帖子,其中包含POST名称 - 值对中重复名称的重复键。

## sample code
payload = {'fname': 'homer', 'lname': 'simpson'
         , 'favefood': 'raw donuts'
         , 'favefood': 'free donuts'
         , 'favefood': 'cold donuts'
         , 'favefood': 'hot donuts'
         }
rtt = requests.post("http://httpbin.org/post", data=payload)



参见



网站链接:

See also

Web links:

  • https://duckduckgo.com/?q=python+requests

  • Trevor如何使用python请求完成此任务?

推荐答案

您可以通过以下方式合成有效负载:

You can composite payload in this way:

payload = [
    ('fname', 'homer'), ('lname', 'simpson'),
    ('favefood', 'raw donuts'), ('favefood', 'free donuts'),
]
rtt = requests.post("http://httpbin.org/post", data=payload)

但是如果你的情况允许,我更喜欢在列表中使用所有'favefoood'POST一个JSON:

But if your case allows, I prefer POST a JSON with all 'favefoood' in a list:

payload = {'fname': 'homer', 'lname': 'simpson', 
    'favefood': ['raw donuts', 'free donuts']
}
# 'json' param is supported from requests v2.4.2
rtt = requests.post("http://httpbin.org/post", json=payload)

或者如果不首选JSON,请将所有'favefood'组合成一个字符串(仔细选择分隔符):

Or if JSON is not preferred, combine all 'favefood' into a string (choose separator carefully):

payload = {'fname': 'homer', 'lname': 'simpson',
    'favefood': '|'.join(['raw donuts', 'free donuts']
}
rtt = requests.post("http://httpbin.org/post", data=payload)

这篇关于处理HTTP post中的重复键以指定多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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