首页 > 解决方案 > 如何从流/渲染字典中压缩 html 文件?

问题描述

我无法通过烧瓶 send_file 下载 html 文件。

  1. 基本上,单独下载一个 html 文件,它工作得很好。通过将流作为参数提供给 send_file 函数

  2. 然而; 我需要将此文件与其他不相关的文件一起放入一个 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")

标签: pythonhtmlflaskzipfilesendfile

解决方案


如果我理解正确,将 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')

推荐阅读