Python请求发布文件 [英] Python requests post a file

查看:29
本文介绍了Python请求发布文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 CURL 我可以发布类似的文件

Using CURL I can post a file like

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

我的文件看起来像

$ cat boot.txt
line 1
line 2
line 3

我正在尝试使用 python 中的 requests 模块来实现相同的目的

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.

推荐答案

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

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()})

这篇关于Python请求发布文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆