【问题标题】:How to upload a text file using Python-Requests without writing to disk如何使用 Python-Requests 上传文本文件而不写入磁盘
【发布时间】:2015-06-29 01:45:36
【问题描述】:

我想在 Python 3 中使用 Python 的 Requests 库在 POST 请求中发送文件。我正在尝试这样发送:

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},
)

但是,服务器响应没有发送任何文件。这应该工作吗?大多数示例都涉及传递文件对象,但我不想为了上传它而将字符串写入磁盘。

【问题讨论】:

    标签: python python-3.x python-requests


    【解决方案1】:

    requests docs 为我们提供了这个:

    如果需要,您可以发送要作为文件接收的字符串:

    >>> 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"
      },
      ...
    }
    

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

    【讨论】:

    • 不错!谢谢,需要写一些测试,每次更改名称/数据。
    【解决方案2】:

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

    【讨论】:

    • 我认为您应该将 ForceBru 的答案标记为已接受。这是您问题的正确答案。它没有回答你的根本问题是不相关的。
    【解决方案3】:

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

    【讨论】:

    • 感谢您的建议。不过,由于我使用的是 Python 3,它位于 io 模块中:io.StringIO
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多