How to upload file with python requests?

I’m performing a simple task of uploading a file using Python requests library. I searched Stack Overflow and no one seemed to have the same problem, namely, that the file is not received by the server:

import requests
url="http://nesssi.cacr.caltech.edu/cgi-bin/getmulticonedb_release2.cgi/post"
files={'files': open('file.txt','rb')}
values={'upload_file' : 'file.txt' , 'DB':'photcat' , 'OUT':'csv' , 'SHORT':'short'}
r=requests.post(url,files=files,data=values)

I’m filling the value of ‘upload_file’ keyword with my filename, because if I leave it blank, it says

Error - You must select a file to upload!

And now I get

File  file.txt  of size    bytes is  uploaded successfully!
Query service results:  There were 0 lines.

Which comes up only if the file is empty. So I’m stuck as to how to send my file successfully. I know that the file works because if I go to this website and manually fill in the form it returns a nice list of matched objects, which is what I’m after. I’d really appreciate all hints.

Some other threads related (but not answering my problem):

  • Send file using POST from a Python script
  • http://docs.python-requests.org/en/latest/user/quickstart/#response-content
  • Uploading files using requests and send extra data
  • http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow

6 Answers
6

Leave a Comment