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

相關問題