I am using Python's requests library to perform a simple task, which is to upload a file. I've searched on Stack Overflow and no one seems to be having the same problem, where the file is not being 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 filled in the value of the 'upload_file' keyword with my filename because if I left it blank it would read:
Error - You must select a file to upload!
Now I get:
The size of file file.txt is bytes, uploaded successfully! Query service results: There are 0 rows in total.
This only occurs if the file is empty. So I don't know how to send my file successfully. I know the file is valid because if I fill out the form manually and visit the site, it returns a nice list of matches, which is exactly what I want. I really appreciate all the tips.
Some other threads that are related (but don't solve my problem):
(2018) The new Python requests library simplifies this process. We can use the 'files' variable to indicate that we want to upload a multi-part encoded file
If
upload_file
refers to a file, use:Then
requests
will send a multipart form POST request body with theupload_file
field set to the contents of thefile.txt
file.The file name will be included in the mime header of the specific field:
Please note the
filename="file.txt"
parameter.If you need more control, you can use tuples as
files
mapping values. The length of the tuple should be between 2 and 4. The first element is the file name, followed by the content, optionally including a mapping of the content-type header and other headers:This will set an alternative filename and content type, omitting the optional headers.
If you want the entire POST request body to come from a file (no other fields are specified), do not use the
files
parameter and POST the file directly asdata
. You may also want to set aContent-Type
header, otherwise no header will be set. SeePython requests - POST data from a file.