如何使用 Sanic 即时下载非常大的 zip 文件?

问题描述 投票:0回答:1

我正在开发一个使用 Sanic 的 Python 应用程序,我需要下载一个非常大的存档(10 GB)。

我正在使用 zipstream 动态创建存档,然后对其进行流式传输(Sanic 支持流式响应)。

类似:

zs = ZipStream()
        for root, _, files in os.walk(file_path):
            for file in files:
                fpath = str(os.path.join(root, file))
                zs.add_path(fpath)

        response = await request.respond(
            headers={'Content-Disposition': f'attachment; filename="{dataset_id}.zip"'},
            content_type='application/zip'
        )

        for chunk in zs:
            await response.send(chunk)

问题是下载到几百MB后就停止了,我不知道为什么。

它的唯一工作方式是使用:

return await sanic.response.file_stream(
            fpath,
            headers={'Content-Disposition': f'attachment; filename="file.zip"'},
        )

但这里的问题是

file_stream()
期望一个真实的文件作为第一个参数(
location: str | PurePath
),我无法从zipstream获取它(我想即时压缩)。

有人知道该怎么做吗?有没有办法模拟文件系统上的文件以使

file_stream()
工作?或者还有别的办法吗?

python python-3.x zip sanic zipstream
1个回答
0
投票

找到解决方案:

await asyncio.sleep(0.001)  # Slight delay between chunks to keep the stream stable
© www.soinside.com 2019 - 2024. All rights reserved.