Python requests publish 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 using the requests module in python

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

      

When I open the file on the 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.

+3


source to share


3 answers


Your rejection request submits the file content as form data, not the actual file! You probably want something like



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

      

+3


source


The two steps you are doing are not the same.

In the first: you explicitly read the file with cat

and pass it to the curl, instructing it to use it as the header value pxeconfig

.

Whereas in the second example you are using multi-page file upload, which is quite different. In this case, the server must parse the received file.

To get the same behavior as the curl command, you should do:



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

      

In contrast, the request curl

if you really want to send a multi-line encoded file looks like this:

curl -F "header=@filepath" url

      

+2


source


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

      

You might want to do something like this so that the files are closed afterwards.

More details here: Submit file using POST with Python script

0


source







All Articles