Python 请求 - POST 文件中的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16145116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python requests - POST data from a file
提问by user2190101
I have used curl to send POST requests with data from files.
我使用 curl 发送带有文件数据的 POST 请求。
I am trying to achieve the same using python requests module. Here is my python script
我正在尝试使用 python requests 模块实现相同的目标。这是我的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
Data file looks like below
数据文件如下所示
'ID' : 'ISM03'
But my script is not POSTing the data from file. Am I missing something here.
但是我的脚本没有从文件中发布数据。我在这里遗漏了什么。
In Curl , I used to have a command like below
在 Curl 中,我曾经有一个像下面这样的命令
Curl --data @filename -ik -X POST 'https://IP_ADDRESS/rest/rest/2'
采纳答案by Martijn Pieters
You do not need to use .read()here, simply stream the object directly. You do need to set the Content-Type header explicitly; curldoes this when using --databut requestsdoesn't:
.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)
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).
我已经将打开的文件对象用作上下文管理器,以便在块退出时它也会自动关闭(例如发生异常或requests.post()成功返回)。

