Handling duplicate keys in an HTTP message to specify multiple values

Background

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

Problem

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

goal

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

Unsuccessful 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:

Question

  • How can Trevor accomplish this task with python queries?
+5
source share
1 answer

You can use such a payload as follows:

 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 JSON with all the "favefoood" in the 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 the "favefood" into a string (carefully select a separator):

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

Source: https://habr.com/ru/post/1207625/


All Articles