问题描述
我已经使用curl来发送带有文件中数据的POST请求.
I have used curl to send POST requests with data from files.
我正在尝试使用python请求模块来实现相同的目的.这是我的python脚本
I am trying to achieve the same using python requests module. Here is my python script
import requests
payload=open('data','rb').read()
r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'), data=payload , verify=False)
print r.text
数据文件如下所示
'ID' : 'ISM03'
但是我的脚本没有从文件中发布数据.我在这里想念什么吗?
But my script is not POSTing the data from file. Am I missing something here.
在Curl中,我曾经有一个类似下面的命令
In Curl , I used to have a command like below
Curl --data @filename -ik -X POST 'https://IP_ADDRESS/rest/rest/2'
推荐答案
此处无需使用.read()
,只需直接流式传输对象即可.您确实需要显式设置Content-Type标头; curl
在使用--data
时会执行此操作,但requests
不会:
You do not need to use .read()
here, simply stream the object directly. You do need to set the Content-Type header explicitly; curl
does this when using --data
but requests
doesn't:
with open('data','rb') as payload:
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'),
data=payload, verify=False, headers=headers)
我将打开文件对象用作上下文管理器,以便在块退出(例如发生异常或requests.post()
成功返回)时也自动为您关闭文件.
I've used the open file object as a context manager so that it is also auto-closed for you when the block exits (e.g. an exception occurs or requests.post()
successfully returns).
这篇关于Python请求-来自文件的POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!