pythonhtmlflaskzipsendfile

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


I am having trouble downloading an html file through the flask send_file.

  1. Basically, to download an html file alone, it works perfectly. by giving the stream to the send_file function as a parameter

  2. However; I need to put this file into a zip along with other unrelated files. There, in the write function, neither the stream nor the string (result_html) work. I need somehow to transform it directly to an html file and put in the zip file

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

Solution

  • 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. The stream can then be transmitted via 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')