python - 如何在请求中流式传输文件?

我们有一个与 django 后端通信的 react 应用程序。每当 react 应用程序想要将文件上传到后端时,我们都会发送一个表单请求,其中一个字段是正在上传的文件的句柄。该字段在 Django 端作为 InMemoryUploadedFile,这是一个带有一些 block 的对象,可以这样处理,例如:

def save_uploaded_file(uploaded_file, handle):
    """
    Saves the uploaded file using the given file handle.
    We walk the chunks to avoid reading the whole file in memory
    """
    for chunk in uploaded_file.chunks():
        handle.write(chunk)
    handle.flush()
    logger.debug(f'Saved file {uploaded_file.name} with length {uploaded_file.size}')

现在,我正在使用 requests 创建一些测试框架来驱动我们的 API。我试图模仿这种机制,但奇怪的是,requests 坚持在发送请求之前从打开的句柄中读取。我正在做:

requests.post(url, data, headers=headers, **kwargs)

与:

data = {'content': open('myfile', 'rb'), ...}

请注意,我不是从文件中读取,我只是打开它。但是requests坚持从里面读取,并发送嵌入的数据,这有几个问题:

  • 它可以很大
  • 由于是二进制数据,它破坏了请求
  • 这不是我的应用程序所期望的

我不想要这个:我想要requests 只是“流式传输”那个文件,而不是读取它。有一个 files 参数,但这将创建一个包含请求中嵌入的文件的多部分,这又不是我想要的。我希望在请求中传递数据中的所有字段,并流式传输内容字段。我知道这是可能的,因为:

  • 浏览器做
  • postman 做
  • django 测试客户端完成

如何强制请求流式传输数据中的特定文件?

最佳答案

可能这不再相关,但我会分享一些我在 documentation 中找到的信息.

By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory. This means that saving the file involves only a read from memory and a write to disk and thus is very fast. However, if an uploaded file is too large, Django will write the uploaded file to a temporary file stored in your system’s temporary directory.

这样就不需要创建流式文件上传了。相反,解决方案可能是使用缓冲区处理(读取)加载的内容。

https://stackoverflow.com/questions/60899318/

相关文章:

javascript - typescript 装饰器 : Add instance field t

scala - 在同一规范文件中测试 akka-http 和 akka actor 时,如何解决冲突

nginx - 为什么我在nginx中无法正常显示CJK字符?

reactjs - 相对于箭头键旋转图像 react js

postgresql - 外键约束问题

spring-boot - 在 spring cloud 配置更新时重新加载 CamelContex

qt - 如何在使用 AUTORCC 的 CMake 项目中使用 qtquick_compiler_

python - np.array 到 PIL 图像 --> Typerror : Cannot h

react-native - 我可以通过 expo 获得在 android 上工作的 webpack

reactjs - AWS 放大自定义问候语