简体   繁体   中英

Python requests post a file

Using CURL I can post a file like

CURL -X POST -d "pxeconfig=`cat boot.txt`" https://ip:8443/tftp/syslinux

My file looks like

$ cat boot.txt
line 1
line 2
line 3

I am trying to achieve the same thing using requests module in python

r=requests.post(url, files={'pxeconfig': open('boot.txt','rb')})

When I open the file on server side, the file contains

{:filename=>"boot.txt", :type=>nil, :name=>"pxeconfig", 
:tempfile=>#<Tempfile:/tmp/RackMultipart20170405-19742-1cylrpm.txt>, 
:head=>"Content-Disposition: form-data; name=\"pxeconfig\"; 
filename=\"boot.txt\"\r\n"}

Please suggest how I can achieve this.

Your curl request sends the file contents as form data, as opposed to an actual file! You probably want something like

with open('boot.txt', 'rb') as f:
    r = requests.post(url, data={'pxeconfig': f.read()})

The two actions you are performing are not the same.

In the first: you explicitly read the file using cat and pass it to curl instructing it to use it as the value of a header pxeconfig .

Whereas, in the second example you are using multipart file uploading which is a completely different thing. The server is supposed to parse the received file in that case.

To obtain the same behavior as the curl command you should do:

requests.post(url, data={'pxeconfig': open('file.txt').read()})

For contrast the curl request if you actually wanted to send the file multipart encoded is like this:

curl -F "header=@filepath" url
with open('boot.txt', 'rb') as f: r = requests.post(url, files={'boot.txt': f})

You would probably want to do something like that, so that the files closes afterwards also.

Check here for more: Send file using POST from a Python script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM