来自requests.py的多部分POST的意外响应

时间:2014-02-17 19:40:29

标签: python python-3.3 python-requests

我正在尝试使用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)

这是来自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": {}
}  

由于某种原因,请求未在“payload”字典中发布所有值。我哪里错了?感谢。

1 个答案:

答案 0 :(得分:3)

字典只能包含唯一的键;您有'name''value'个重复的密钥。

如果您有重复的参数,请使用(键,值)对的列表:

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

请注意,httpbin.org 使用字典来表示发布的值,当它回传给您时,您将看不到那里反映的更改。

POST主体包含以下内容:

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

当你使用这样的元组列表时。