Reputation: 1451
I am trying to send multiple files in a post request. Following is the code I use.
orig_src = "./orig_src/"
url = "http://"+server+":"+port+"/my_service"
files = []
for root, dirs, files in os.walk(orig_src):
for fileName in files:
if len(files) > 0:
relDir = os.path.relpath(root, orig_src)
relFile = os.path.join(relDir, fileName)
files.append(('srcFile', (fileName, open(orig_src+relFile, 'rb'))))
response = requests.post(url, files = files)
I get the following error when I try to do this:
File "/usr/lib/python2.7/posixpath.py", line 66, in join
if b.startswith('/'):
AttributeError: 'tuple' object has no attribute 'startswith'
Any idea where the error might be? earlier I created a curl request using -F option and ran it using os.system command. That was running fine. But I am not able to send the post request now. where am i going wrong?
Upvotes: 2
Views: 2372
Reputation: 28777
You're passing a tuple to os.path.join
as the traceback explains (in join
).
You need a better name for the list that you're passing to requests because you are reusing the name files
after you declare it as an empty list.
files
as an empty list in line 3files
as the third item you receive from the tuple you're unpacking in your for loop on line 4.Since you're modifying files
in place, you're adding tuples to the list. Python expects that you understand this and eventually iterates through the list until it reaches the first tuple. In this case fileName
is now a tuple and you pass that to os.path.join
which expects a string, not a tuple.
Change one of the two bindings and you should be fine.
Upvotes: 1