How to upload files using Python's requests library?
P粉071559609
2023-08-16 18:44:37
<p>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: </p>
<pre class="brush:php;toolbar:false;">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)</pre>
<p>I filled in the value of the 'upload_file' keyword with my filename because if I left it blank it would read: </p>
<pre class="brush:php;toolbar:false;">Error - You must select a file to upload! </pre>
<p>Now I get: </p>
<pre class="brush:php;toolbar:false;">The size of file file.txt is bytes, uploaded successfully!
Query service results: There are 0 rows in total. </pre>
<p>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. </p>
<p>Some other threads that are related (but don't solve my problem): </p>
<ul>
<li>Use a Python script to send files via POST</li>
<li>http://docs.python-requests.org/en/latest/user/quickstart/#response-content</li>
<li>Use requests to upload files and send additional data</li>
<li>http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow</li>
</ul><p><br /></p>
(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.