Python中的复杂POST请求 - 多部分文件 - 解压缩的值太多

时间:2017-11-23 12:45:21

标签: python python-3.x post python-requests multipartform-data

我试图以下列模式将一些文件和参数作为Multi-Part发布。我已经尝试过dict和list。 list投了一个HTTP 415。所以我继续dict。我想在一个通用名称'file'下发布一些参数和多个文件(以及它们各自的文件名)。

字符串参数工作正常,错误在于文件上传

在多部分dict对象中传递的数据

multipart = {
    'param1': 'paramVal1',
    'param2': 'paramVal2',
    'file': (("file1.xml", ByteIO), ("file1.xml", ByteIO)),
}

使用python-requests

进行发布
requests.post(url='http://localhost:8888/upload',files=multipart)

引发错误

File "C:\Python36\lib\site-packages\requests\api.py", line 107, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Python36\lib\site-packages\requests\api.py", line 53, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python36\lib\site-packages\requests\sessions.py", line 454, in request
    prep = self.prepare_request(req)
  File "C:\Python36\lib\site-packages\requests\sessions.py", line 388, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Python36\lib\site-packages\requests\models.py", line 296, in prepare
    self.prepare_body(data, files, json)
  File "C:\Python36\lib\site-packages\requests\models.py", line 447, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "C:\Python36\lib\site-packages\requests\models.py", line 142, in _encode_files
    fn, fp, ft, fh = v
ValueError: too many values to unpack (expected 4)

预期的POST正文

------WebKitFormBoundaryZ7HAof4KTgAB21YV
Content-Disposition: form-data; name="file"; filename="file1.xml"
Content-Type: text/xml


------WebKitFormBoundaryZ7HAof4KTgAB21YV
Content-Disposition: form-data; name="file"; filename="file2.xml"
Content-Type: text/xml


------WebKitFormBoundaryZ7HAof4KTgAB21YV
Content-Disposition: form-data; name="param1"

paramVal1
------WebKitFormBoundaryZ7HAof4KTgAB21YV
Content-Disposition: form-data; name="param2"

paramVal2
------WebKitFormBoundaryZ7HAof4KTgAB21YV--

2 个答案:

答案 0 :(得分:3)

由于两个文件项具有相同的名称,因此无法使用字典,但您可以在SELECT [Client Code] = Client_Code, [Client Name] = Client_Name, [Post Haircut Stock] = POST_HC_STK FROM TableA 参数中使用元组列表。
对于表单数据的其余部分,请使用files参数。

data

请求正文:

data = {
    'param1': 'paramVal1',
    'param2': 'paramVal2'
}
files = [
    ("file", ("file1.xml", open("file1.xml", "rb"), "text/xml")), 
    ("file", ("file2.xml", open("file2.xml", "rb"), "text/xml"))
]
r = requests.post(url='http://localhost:8888/upload', data=data, files=files)

print(r.request.body)

答案 1 :(得分:-1)

'参数1'和' param2'不是正确的文件吗?

您的请求应如下所示:

body = {'param1': 'paramVal1', 'param2': 'paramVal2'}
files = (("file1.xml", ByteIO), (filename, "file2.xml")),
requests.post(url='http://localhost:8888/upload', files = files, json = body)