roy
roy

Reputation: 23

upload a file using python requests module

I am trying to upload a file using python requests module and i am not sure whether we can use both data and files in the post call.

fileobj= open(filename,'rb')
upload_data = {
    'data':payload,
    'file':fileobj
}

resp = s.post(upload_url,data=upload_data,headers=upload_headers)

and this is not working. So can anyone help me with this ?

Upvotes: 2

Views: 626

Answers (1)

wpercy
wpercy

Reputation: 10090

I think you should be using the data and files keyword parameters in the post request to send the data and file respectively.

with open(filename,'rb') as fileobj:
    files = {'file': fileobj}
    resp = s.post(upload_url,data=payload,files=files,headers=upload_headers)

I've also use a context manager just because it closes the file for me and takes care of exceptions that happen either during file opening or during something that happens with the requests post.

Upvotes: 1

Related Questions