如何在不写入磁盘的情况下使用 Python-Requests 上传文本文件
How to upload a text file using Python-Requests without writing to disk
我想在 Python 中使用 Python 的请求库在 POST
请求中发送一个文件,在 Python 3. 我正在尝试这样发送它:
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},
)
服务器响应说没有文件被发送,但是。这应该工作吗?大多数示例涉及传递一个文件对象,但我不想为了上传它而将字符串写入磁盘。
为什么不使用 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)},
)
我认为requests
使用了一些类似于我们处理文件的方法。 cStringIO
提供它们。
用法示例
>>> from cStringIO import *
>>> a=StringIO("hello")
>>> a.read()
'hello'
requests
docs 为我们提供了这个:
If you want, you can send strings to be received as files:
>>> 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"
},
...
}
我将其作为另一个答案发布,因为它涉及不同的方法。
事实证明,它不工作的原因与文件内容无关,而是我通过 HTTP 发送请求,而不是 HTTPS,这会丢失请求的整个主体。
我想在 Python 中使用 Python 的请求库在 POST
请求中发送一个文件,在 Python 3. 我正在尝试这样发送它:
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},
)
服务器响应说没有文件被发送,但是。这应该工作吗?大多数示例涉及传递一个文件对象,但我不想为了上传它而将字符串写入磁盘。
为什么不使用 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)},
)
我认为requests
使用了一些类似于我们处理文件的方法。 cStringIO
提供它们。
用法示例
>>> from cStringIO import *
>>> a=StringIO("hello")
>>> a.read()
'hello'
requests
docs 为我们提供了这个:
If you want, you can send strings to be received as files:
>>> 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"
},
...
}
我将其作为另一个答案发布,因为它涉及不同的方法。
事实证明,它不工作的原因与文件内容无关,而是我通过 HTTP 发送请求,而不是 HTTPS,这会丢失请求的整个主体。