handling duplicate keys in HTTP post in order to specify multiple values

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 15:57:47

问题


Background

  • python 2.7
  • requests module
  • http post with duplicate keys to specify multiple values

Problem

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.

Goal

  • The goal is to use python requests to create an HTTP post with duplicate keys for duplicate names in the POST name-value pairs.

Failed attempts

## 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

Question

  • How can Trevor accomplish this task using python requests?

回答1:


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)

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)

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)


来源:https://stackoverflow.com/questions/27116424/handling-duplicate-keys-in-http-post-in-order-to-specify-multiple-values

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