metalayer
metalayer

Reputation: 69

Unexpected response from multi-part POST with requests.py

I'm trying to POST a multi-part encoded form with requests in python 3.3

payload = {'name':'username','value':'m3ta','name':'password','value':'xxxxxxxx'}
files = {'c_file': open(saveimg, 'rb')}
sendc = requests.post("http://httpbin.org/post", data = payload, files = files)
response = sendc.text
print (response)

This is the post content from httpbin..

{
  "json": null,
  "files": {
    "c_file": "data:image/x-png;base64,(lots of binary data)},
  "form": {
    "value": "xxxxxxxx",
    "name": "password"
  },
  "headers": {
    "Heroku-Request-Id": "c101bf2e-d69a-4aab-ac15-b9005a7bcebe",
    "Accept": "*/*",
    "Accept-Encoding": "identity, gzip, deflate, compress",
    "Content-Type": "multipart/form-data; boundary=c5b1e65ff0ac46029c88b9661f981534",
    "Connection": "close",
    "Host": "httpbin.org",
    "X-Request-Id": "c101bf2e-d69a-4aab-ac15-b9005a7bcebe",
    "Content-Length": "12262",
    "User-Agent": "python-requests/1.2.3 CPython/3.3.2 Windows/7"
  },
  "origin": "81.107.44.15",
  "data": "",
  "url": "http://httpbin.org/post",
  "args": {}
}  

For some reason requests is not posting all the values in the "payload" dictionary. Where am I going wrong? Thanks.

Upvotes: 0

Views: 215

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

Dictionaries can only hold unique keys; you have duplicate 'name' and 'value' keys.

Use a list of (key, value) pairs instead if you have duplicate parameters:

payload = [
    ('name', 'username'), ('value', 'm3ta'),
    ('name', 'password'), ('value', 'xxxxxxxx'),
]

Note that httpbin.org also uses a dictionary to represent posted values when it echos them back to you, so you won't see the change reflected there.

The POST body however will contain something along the lines of:

--36ae094926114bed8aa5518ba2e949a4
Content-Disposition: form-data; name="name"

username
--36ae094926114bed8aa5518ba2e949a4
Content-Disposition: form-data; name="value"

m3ta
--36ae094926114bed8aa5518ba2e949a4
Content-Disposition: form-data; name="name"

password
--36ae094926114bed8aa5518ba2e949a4
Content-Disposition: form-data; name="value"

xxxxxxxx

when you use a list of tuples like this.

Upvotes: 3

Related Questions