如何使用Python-Requests上传文本文件而无需写入磁盘

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)

但是,服务器响应没有发送文件.这有用吗?大多数示例涉及传递文件对象,但我不想将字符串写入磁盘只是为了上传它.

For*_*Bru 7

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)

我将其作为另一个答案发布,因为它涉及不同的方法.


For*_*Bru 5

为什么不使用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)

  • 谢谢你的建议。不过,由于我使用的是 Python 3,它位于 `io` 模块中:`io.StringIO` (2认同)

Dov*_*Dov -3

事实证明,它不起作用的原因与文件内容无关,而是因为我通过 HTTP 而不是 HTTPS 发送请求,后者丢失了请求的整个正文。

  • 我认为您应该将 ForceBru 的答案标记为已接受。这是您问题的正确答案。它没有回答您的根本问题是不相关的。 (3认同)