file-upload - 请求 - 如何在请求中上传大块文件?
问题描述
我必须上传大文件(~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 没有大量内存使用。
解决方案
这就是文档所说的:
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
.
推荐阅读
- ios - Travis CI 上的 iOS 排毒测试失败
- java - 矩阵乘法中的越界异常
- github - 为什么 Azure 管道突然停止出现在 GitHub 上的 PR(开源、公开)?
- linux - 接收 stdin 并调用以在 linux 中打开常规文件
- javascript - 无法在循环中设置未定义的属性“innerHTML”
- javascript - jQuery div 重新加载并在以下页面上使用 Get 提交 - 时间问题 - dhtml 调度程序
- sql-server - 计算清理了多少字段以及 SSIS 上的哪些字段
- python - 模块导入,但没有任何属性
- c++ - 如何在 C++ 中创建一个指针数组
- c# - 在抛出 C# 异常时使用 SMTP 客户端:System.UriFormatException