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中的 请求 模块来实现相同的目的

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

请提出如何实现这一目标。


问题答案:

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

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