2

With requests,当使用POST和简单数据时,我可以为多个值使用相同的名称。 curl命令:如何使用请求提交具有相同POST名称的多个文件?

curl --data "source=contents1&source=contents2" example.com 

可以翻译成:

data = {'source': ['contents1', 'contents2']} 
requests.post('example.com', data) 

同样不处理文件。如果我翻译工作curl命令:

curl --form "[email protected]/file1.txt" --form "[email protected]/file2.txt" example.com 

到:收到

with open('file1.txt') as f1, open('file2.txt') as f2: 
    files = {'source': [f1, f2]} 
    requests.post('example.com', files=files) 

只有最后一个文件。

MultiDict from werkzeug.datastructures也没有帮助。

如何使用相同的POST名称提交多个文件?

回答

6

不要使用字典,使用元组列表;每个元组一个(name, file)对:

files = [('source', f1), ('source', f2)] 

file元件可以与有关该文件的更详细的另一个元组;包括文件名和MIME类型,你可以这样做:

files = [ 
    ('source', ('f1.ext', f1, 'application/x-example-mimetype'), 
    ('source', ('f2.ext', f2, 'application/x-example-mimetype'), 
] 

这在文档的高级用法POST Multiple Multipart-Encoded Files section被记录在案。

+0

为什么不用字典? – avi 2014-10-19 03:39:06

+0

@avi:因为你不能在字典中重复键。值列表选项是['urllib.urlencode()'函数](https://docs.python.org/2/library/urllib.html#urllib.urlencode)的一个特性,它不用于多部分文件上传。 – 2014-10-19 03:41:29

+0

啊哈,有道理。谢谢。 – avi 2014-10-19 03:42:28

相关问题