【问题标题】:Requests - How to upload large chunks of file in requests?请求 - 如何在请求中上传大块文件?
【发布时间】:2021-09-19 20:18:39
【问题描述】:

我必须上传大文件 (~5GB)。我将文件分成小块(10MB),无法一次发送所有数据(+5GB)(因为如果在一个请求中发送超过 5GB 的大数据,我请求的 api 将失败)。我上传到的 api 有一个规范,它需要至少 10MB 的数据才能发送。我确实使用了 read(10485760) 并通过请求发送它,效果很好。

但是,我不想读取内存中的所有 10MB,如果我在脚本中利用多线程,那么读取 10MB 的每个线程都会占用太多内存。

有没有一种方法可以向 api 请求发送总共 10MB 但一次只读取 4096/8192 字节并传输直到达到 10MB,这样我就不会过度使用内存。

请注意,我无法在请求中发送 fileobj,因为这将使用更少的内存,但我将无法在 10MB 处破坏块,并且整个 5GB 数据将发送到请求中,这是我不想要的。

有没有办法通过请求。我看到httplib有它。 https://github.com/python/cpython/blob/3.9/Lib/http/client.py - 我将在这里循环调用 send(fh.read(4096) 函数,直到我完成 10MB 并且将完成一个 10MB 的请求而不会占用大量内存。

【问题讨论】:

    标签: file-upload python-requests upload streaming


    【解决方案1】:

    这就是文档所说的: In the event you are posting a very large file as a multipart/form-data request, you may want to stream the request. By default, requests does not support this, but there is a separate package which does - requests-toolbelt. You should read the toolbelt’s documentation for more details about how to use it.

    所以尝试stream 上传,如果它不能满足您的需要,然后去requests-toolbelt

    为了stream上传,你需要在函数调用中传递stream=True,无论是post还是put

    【讨论】:

    • “尝试流式传输”上传是什么意思?如何做到这一点..传递fileobj,无助于仅读取选定的字节然后上传。它将读取整个文件。另外,我没有表格,所以不确定“multipart/form-data”,只是我想将文件分成多个部分并上传。
    猜你喜欢
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2017-10-11
    • 2021-08-10
    • 2019-05-20
    • 2018-08-28
    • 2020-08-11
    • 1970-01-01
    相关资源
    最近更新 更多