【问题标题】:Stream multiple files at once from a Django server从 Django 服务器一次流式传输多个文件
【发布时间】:2021-01-18 00:44:44
【问题描述】:

我正在运行一个 Django 服务器来提供来自受保护网络中另一台服务器的文件。当用户请求一次访问多个文件时,我希望我的 Django 服务器一次将这些文件全部流式传输给该用户。

由于在浏览器中一次下载多个文件并不容易,因此需要以某种方式捆绑文件。我不希望我的服务器必须先下载所有文件,然后再提供准备好的捆绑文件,因为这会为较大的文件增加大量时间损失。有了拉链,我的理解是它在组装时不能流式传输。

有什么方法可以在远程服务器的第一个字节可用后立即开始流式传输容器?

【问题讨论】:

    标签: python django django-views zip tar


    【解决方案1】:

    Tar 文件用于将多个文件收集到一个存档中。它们是为录音机开发的,因此提供顺序写入和读取。

    使用 Django,可以使用 FileResponse() 将文件流式传输到浏览器,它可以将生成器作为参数。

    如果我们为它提供一个生成器,该生成器将 tar 文件与用户请求的数据组合起来,tar 文件将及时生成。然而,python 内置的 tarfile-module 并没有提供这种开箱即用的功能。

    然而,我们可以利用tarfile 的能力来传递一个类似文件的对象来自己处理档案的组装。因此,我们可以创建一个 BytesIO() 对象,tarfile 将逐渐写入该对象并将其内容刷新到 Django 的 FileResponse() 方法。为此,我们需要实现FileResponse()tarfile 期望访问的一些方法。让我们创建一个类FileStream

    class FileStream:
        def __init__(self):
            self.buffer = BytesIO()
            self.offset = 0
    
        def write(self, s):
            self.buffer.write(s)
            self.offset += len(s)
    
        def tell(self):
            return self.offset
    
        def close(self):
            self.buffer.close()
    
        def pop(self):
            s = self.buffer.getvalue()
            self.buffer.close()
            self.buffer = BytesIO()
            return s
    

    现在,当我们将write() 数据发送到FileStream 的缓冲区和yield FileStream.pop() 时,Django 会立即将该数据发送给用户。

    作为数据,我们现在要组装该 tar 文件。在FileStream 类中我们添加了另一个方法:

        @classmethod
        def yield_tar(cls, file_data_iterable):
            stream = FileStream()
            tar = tarfile.TarFile.open(mode='w|', fileobj=stream, bufsize=tarfile.BLOCKSIZE)
    

    这会在内存中创建一个FileStream-instance 和一个文件句柄。文件句柄访问FileStream-instance 来读取和写入数据,而不是访问磁盘上的文件。

    现在在 tar 文件中,我们首先必须添加一个 tarfile.TarInfo() 对象,该对象代表顺序写入数据的标头,包含文件名、大小和修改时间等信息。

            for file_name, file_size, file_date, file_data in file_data_iterable:
                tar_info = tarfile.TarInfo(file_name)
                tar_info.size = int(file_size)
                tar_info.mtime = file_date
                tar.addfile(tar_info)
                yield stream.pop()
    

    您还可以查看将任何数据传递给该方法的结构。 file_data_iterable 是包含
    ((str) file_name, (int/str) file_size, (str) unix_timestamp, (bytes) file_data)的元组列表。

    发送 TarInfo 后,遍历 file_data。 此数据需要是可迭代的。 例如,您可以使用通过 requests.get(url, stream=True) 检索的 requests.response 对象。

                for chunk in (requests.get(url, stream=True).iter_content(chunk_size=cls.RECORDSIZE)):
                    # you can freely choose that chunk size, but this gives me good performance
                    tar.fileobj.write(chunk)
                    yield stream.pop()
    

    注意:这里我使用变量url 来请求文件。您需要在元组参数中传递它而不是 file_data。如果你选择传入一个可迭代的文件,你需要更新这一行。

    最后,tarfile 需要一种特殊格式来指示文件已完成。 Tarfile 由块和记录组成。通常一个块包含 512 字节,一条记录包含 20 个块(20*512 字节 = 10240 字节)。首先,包含最后一块文件数据的最后一个块被 NUL(通常是纯零)填充,然后下一个文件的下一个 TarInfo 头开始。

    要结束存档,当前记录将被 NUL 填充,但必须至少有两个块完全被 NUL 填充。这将由tar.close() 处理。另见Wiki

                blocks, remainder = divmod(tar_info.size, tarfile.BLOCKSIZE)
                if remainder > 0:
                    tar.fileobj.write(tarfile.NUL * (tarfile.BLOCKSIZE - remainder))
                    yield stream.pop()
                    blocks += 1
                tar.offset += blocks * tarfile.BLOCKSIZE
            tar.close()
            yield stream.pop()
    

    您现在可以在 Django 视图中使用 FileStream 类:

    from django.http import FileResponse
    import FileStream
    
    def stream_files(request, files):
        file_data_iterable = [(
            file.name,
            file.size,
            file.date.timestamp(),
            file.data
        ) for file in files]
    
        response = FileReponse(
            FileStream.yield_tar(file_data_iterable),
            content_type="application/x-tar"
        )
        response["Content-Disposition"] = 'attachment; filename="streamed.tar"'
        return response
    

    如果您想传递 tar 文件的大小以便用户可以看到进度条,您可以提前确定未压缩的 tar 文件的大小。在FileStream 类中添加另一个方法:

        def tarsize(cls, sizes):
            # Each file is preceeded with a 512 byte long header
            header_size = 512
            # Each file will be appended to fill up a block
            tar_sizes = [ceil((header_size + size) / tarfile.BLOCKSIZE)
                         * tarfile.BLOCKSIZE for size in sizes]
            # the end of the archive is marked by at least two consecutive
            # zero filled blocks, and the final record block is filled up with
            # zeros.
            sum_size = sum(tar_sizes)
            remainder = cls.RECORDSIZE - (sum_size % cls.RECORDSIZE)
            if remainder < 2 * tarfile.BLOCKSIZE:
                sum_size += cls.RECORDSIZE
            total_size = sum_size + remainder
            assert total_size % cls.RECORDSIZE == 0
            return total_size
    

    并使用它来设置响应头:

    tar_size = FileStream.tarsize([file.size for file in files])
    ...
    response["Content-Length"] = tar_size
    

    非常感谢chipx86allista,他们的要点帮助我完成了这项任务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 2018-04-02
      • 2014-08-08
      • 2014-11-15
      • 1970-01-01
      相关资源
      最近更新 更多