6

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.

user1191140
  • 1,559
  • 3
  • 18
  • 37

3 Answers3

10

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()})
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
2

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
xrisk
  • 3,790
  • 22
  • 45
1
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

Community
  • 1
  • 1
Akame
  • 11
  • 1
  • 4
  • This is the correct pattern for posting files, but in this case OP wants to post the contents of the file, not the file itself, it seems. – ggorlen Jan 27 '21 at 23:51