我正在开发一个使用 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()
工作?或者还有别的办法吗?
找到解决方案:
await asyncio.sleep(0.001) # Slight delay between chunks to keep the stream stable