Python 请求 - POST 文件中的数据 [英] Python requests - POST data from a file

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

问题描述

我使用 curl 发送带有文件数据的 POST 请求.

I have used curl to send POST requests with data from files.

我正在尝试使用 python requests 模块实现相同的目标.这是我的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 文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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