Dov*_*Dov 7 python python-3.x python-requests
我想POST在Python 3中使用Python的Requests库在请求中发送一个文件.我试图像这样发送它:
import requests
file_content = 'This is the text of the file to upload'
r = requests.post('http://endpoint',
params = {
'token': 'api_token',
'message': 'message text',
},
files = {'filename': file_content},
)
Run Code Online (Sandbox Code Playgroud)
但是,服务器响应没有发送文件.这有用吗?大多数示例涉及传递文件对象,但我不想将字符串写入磁盘只是为了上传它.
该requests文档为我们提供了这一点:
如果需要,您可以发送要作为文件接收的字符串:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}
Run Code Online (Sandbox Code Playgroud)
我将其作为另一个答案发布,因为它涉及不同的方法.
为什么不使用cStringIO?
import requests, cStringIO
file_content = 'This is the text of the file to upload'
r = requests.post('http://endpoint',
params = {
'token': 'api_token',
'message': 'tag_message',
},
files = {'filename': cStringIO.StringIO(file_content)},
)
Run Code Online (Sandbox Code Playgroud)
我认为requests使用一些类似于我们使用文件的方法。cStringIO提供它们。
使用示例
>>> from cStringIO import *
>>> a=StringIO("hello")
>>> a.read()
'hello'
Run Code Online (Sandbox Code Playgroud)
Dov*_*Dov -3
事实证明,它不起作用的原因与文件内容无关,而是因为我通过 HTTP 而不是 HTTPS 发送请求,后者丢失了请求的整个正文。
| 归档时间: |
|
| 查看次数: |
3958 次 |
| 最近记录: |