Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 687
dreftymac Avatar asked Nov 24 '14 23:11

dreftymac


People also ask

Does HashMap allow duplicate keys?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

What happens if we insert duplicate key in HashMap?

If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.

Can keys be repeated?

Why you can not have duplicate keys in a dictionary? You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.


Video Answer


1 Answers

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)
like image 56
ZZY Avatar answered Oct 13 '22 15:10

ZZY