简体   繁体   English

如何从流/渲染字典中压缩 html 文件?

[英]How to zip an html file from a stream/rendered dictionary?

I am having trouble downloading an html file through the flask send_file.我在通过flask send_file 下载html 文件时遇到问题。

  1. Basically, to download an html file alone, it works perfectly.基本上,单独下载一个 html 文件,它完美地工作。 by giving the stream to the send_file function as a parameter通过将流作为参数提供给 send_file 函数

  2. However;然而; I need to put this file into a zip along with other unrelated files.我需要将此文件与其他不相关的文件一起放入 zip 文件中。 There, in the write function, neither the stream nor the string (result_html) work.在那里,在 write 函数中,流和字符串 (result_html) 都不起作用。 I need somehow to transform it directly to an html file and put in the zip file我需要以某种方式将其直接转换为 html 文件并放入 zip 文件

I don't see how I could do this for the moment.我暂时不知道如何做到这一点。 I have the data (output) as a dict...我将数据(输出)作为字典...

Thank you if you have any pointers如有指点,谢谢

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")

If I understand you correctly, it is sufficient to write the zip file in a stream and add the result of the rendering as a character string to the zip file.如果我理解正确,将 zip 文件写入流中并将渲染结果作为字符串添加到 zip 文件中就足够了。 The stream can then be transmitted via send_file.然后可以通过 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM