首页 > 解决方案 > 请求 - 如何在请求中上传大块文件?

问题描述

我必须上传大文件(~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-uploadpython-requestsuploadstreaming

解决方案


这就是文档所说的: 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.


推荐阅读