gpt4 book ai didi

python - 压缩并服务器多个内存中文件

转载 作者:行者123 更新时间:2023-12-02 03:47:30 26 4
gpt4 key购买 nike

我目前正在使用下面的代码生成一个Word文档,然后使用cherrypy在网络上提供该文档。

tpl.get_docx().save(iostream)
cherrypy.response.headers['Content-Type'] = (
'application/vnd.openxmlformats-officedocument'
'.wordprocessingml.document'
)
cherrypy.response.headers['Content-Disposition'] = (
'attachment; filename={fname}.docx'.format(
fname='SP' + kwargs['sp'] + '-'+ kwargs['WO'] + ' ' + kwargs['site'] + ' - ' + 'RPC Report' +'.docx'
)
)
iostream.seek(0)
return file_generator(iostream)

我计划创建更多文档,然后将它们压缩到内存中,然后在网络上提供它们。这是如何实现的,我尝试过使用 zipfile 库,压缩内存文件似乎很复杂。

我用谷歌搜索的以下示例可能会解决我的问题,但不确定如何使用它。

import zipfile
import StringIO

zipped_file = StringIO.StringIO()
with zipfile.ZipFile(zipped_file, 'w') as zip:
for i, file in enumerate(files):
file.seek(0)
zip.writestr("{}.csv".format(i), file.read())

zipped_file.seek(0)

最佳答案

经过几个小时的坚持,我成功了,是啊

iostream = BytesIO()
tpl.get_docx().save(iostream)

iostream1 = BytesIO()
tpl1.get_docx().save(iostream1)

zip_output = StringIO.StringIO()
file = zipfile.ZipFile(zip_output, "w")
file.writestr("test.docx", iostream.getvalue())
file.writestr("test1.docx", iostream1.getvalue())
file.close()

cherrypy.response.headers['Content-Type'] = 'application/zip'
cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="test.zip"'

return zip_output.getvalue()

关于python - 压缩并服务器多个内存中文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com