python - 如何从流/渲染字典中压缩 html 文件?
问题描述
我无法通过烧瓶 send_file 下载 html 文件。
基本上,单独下载一个 html 文件,它工作得很好。通过将流作为参数提供给 send_file 函数
然而; 我需要将此文件与其他不相关的文件一起放入一个 zip 文件中。在那里,在 write 函数中,流和字符串 (result_html) 都不起作用。我需要以某种方式将其直接转换为 html 文件并放入 zip 文件
我暂时不知道我怎么能做到这一点。我将数据(输出)作为字典...
如果有什么指点谢谢
from flask import render_template, send_file
from io import BytesIO
result_html = render_template('myResult.html', **output)
result_stream = BytesIO(str(result_html).encode())
with ZipFile("zipped_result.zip", "w") as zf:
zf.write(result_html)
# zf.write(other_files)
send_file(zf, as_attachment=True, attachment_filename="myfile.zip")
解决方案
如果我理解正确,将 zip 文件写入流中并将渲染结果作为字符串添加到 zip 文件中就足够了。然后可以通过 send_file 传输流。
from flask import render_template, send_file
from io import BytesIO
from zipfile import ZipFile
# ...
@app.route('/download')
def download():
output = { 'name': 'Unknown' }
result_html = render_template('result.html', **output)
stream = BytesIO()
with ZipFile(stream, 'w') as zf:
zf.writestr('result.html', result_html)
# ...
stream.seek(0)
return send_file(stream, as_attachment=True, attachment_filename='archive.zip')
推荐阅读
- swift - 到目前为止,枚举似乎没用。你能举个例子说明为什么他们不是吗?
- javascript - JSX props 不使用内联箭头函数的解决方案?
- r - 动态渲染 R 闪亮框中的标题
- javascript - 温斯顿记录器在nodejs中不起作用
- elasticsearch - Elasticsearch 6自引用循环错误
- tensorflow - opencv 和 tensorflow 都使用 libgtk 时的分段错误
- c++ - 在 CMake 中使用 Log4cxx
- android - 完成活动时跳过后堆栈中的项目?
- laravel - 如何在 vue + laravel 中查看多语言
- php - mysqli fetch_assoc() 没有发布