python - 从 Django 服务器一次流式传输多个文件

标签 python django django-views zip tar

我正在运行 Django 服务器来从 protected 网络中的另一台服务器提供文件。当用户请求一次访问多个文件时,我希望我的 Django 服务器一次性将这些文件全部传输给该用户。
由于在浏览器中一次下载多个文件并不容易,因此需要以某种方式捆绑文件。我不希望我的服务器必须先下载所有文件,然后再提供一个现成的捆绑文件,因为这会为较大的文件增加很多时间损失。对于 zip,我的理解是它在组装时不能流式传输。
一旦来自远程服务器的第一个字节可用,有没有办法开始流式传输容器?

最佳答案

tar 文件用于将多个文件收集到一个存档中。它们是为磁带录音机开发的,因此提供顺序写入和读取。
使用 Django,可以使用 FileResponse() 将文件流式传输到浏览器,它可以将生成器作为参数。
如果我们为它提供一个生成器,该生成器将 tar 文件与用户请求的数据组合在一起,那么 tar 文件将及时生成。然而pythons内置 tarfile -module 不提供这种开箱即用的功能。
但是我们可以使用 tarfile的能力传递一个类似 File 的对象来自己处理文件的组装。因此,我们可以创建一个 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()表示顺序写入数据的 header 的对象,包含文件名、大小和修改时间等信息。
        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.response您使用 requests.get(url, stream=True) 检索的对象.
            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 需要一种特殊格式来指示文件已完成。 Tarfiles 由块和记录组成。通常一个块包含 512 个字节,一个记录包含 20 个块(20*512 个字节 = 10240 个字节)。首先包含最后一块文件数据的最后一个块用 NUL(通常是纯零)填充,然后下一个文件的下一个 TarInfo header 开始。
要结束存档,当前记录将被 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()

您现在可以使用 FileStream Django View 中的类:
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他的要点对我完成这项任务有很大帮助。

关于python - 从 Django 服务器一次流式传输多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64169858/

相关文章:

django - 'QueryDict' 对象在 Django 中没有属性 'caption'

python - 从 3d 数组中提取 2d 面片

python - Windows 上线程和 PyGTK 的执行顺序

python - 向量化模糊图像的 Python 函数

Django CSRF 验证

python - 在 django 中保存对象列表

python - 如何实时更新 django 模板?

python - 如何使用 django-redis 访问其余的较低 namespace ?

python - 发送 2 个参数到 Celery eta 任务

python - 在 Django 中检查 M2M 交叉点的有效方法?