Python请求发布一个fi

2024-05-19 12:51:35 发布

您现在位置:Python中文网/ 问答频道 /正文

使用CURL我可以像

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

我的文件看起来像

$ cat boot.txt
line 1
line 2
line 3

我正试图使用python中的requests模块实现同样的功能

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

当我在服务器端打开文件时,该文件包含

{: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"}

请建议我如何做到这一点。


Tags: 文件namehttpsiptxtlinecurlfilename
3条回答

您正在执行的两个操作不相同。

第一步:使用cat显式读取文件,并将其传递给curl,指示它将其用作头pxeconfig的值。

然而,在第二个例子中,您使用的是多部分文件上传,这是完全不同的事情。在这种情况下,服务器应该解析接收到的文件。

要获得与curl命令相同的行为,应执行以下操作:

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

相比之下,如果您真的想发送文件multipart encoded,那么curl请求如下:

curl -F "header=@filepath" url

curl请求将文件内容作为表单数据发送,而不是实际的文件!你可能想要像

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

你可能想做这样的事情,这样文件也会在之后关闭。

在这里查看更多信息:Send file using POST from a Python script

相关问题 更多 >