Uploading multiple files in a single request using python requests module

user462455 picture user462455 · Aug 12, 2013 · Viewed 39.3k times · Source

The Python requests module provides good documentation on how to upload a single file in a single request:

 files = {'file': open('report.xls', 'rb')}

I tried extending that example by using this code in an attempt to upload multiple files:

 files = {'file': [open('report.xls', 'rb'), open('report2.xls, 'rb')]}

but it resulted in this error:

 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py",      line 1052, in splittype
 match = _typeprog.match(url)
 TypeError: expected string or buffer

Is it possible to upload a list of files in a single request using this module, and how?

Answer

Ryan Fau picture Ryan Fau · Dec 25, 2013

To upload a list of files with the same key value in a single request, you can create a list of tuples with the first item in each tuple as the key value and the file object as the second:

files = [('file', open('report.xls', 'rb')), ('file', open('report2.xls', 'rb'))]