use*_*101 17 python file python-requests
我使用curl发送带有文件数据的POST请求.
我正在尝试使用python请求模块实现相同的功能.这是我的python脚本
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
Run Code Online (Sandbox Code Playgroud)
数据文件如下所示
'ID' : 'ISM03'
Run Code Online (Sandbox Code Playgroud)
但我的脚本不是从文件中发布数据.我在这里错过了一些东西.
在Curl中,我曾经有过如下命令
Curl --data @filename -ik -X POST 'https://IP_ADDRESS/rest/rest/2'
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 38
您无需在.read()此处使用,只需直接传输对象即可.您需要显式设置Content-Type标头; curl在使用时这样做--data但requests不是:
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)
Run Code Online (Sandbox Code Playgroud)
我已经使用open文件对象作为上下文管理器,这样当块退出时它也会自动关闭(例如发生异常或requests.post()成功返回).