Downloading flask-generated html page

Question:

I want to put a button on a flask-generated web page and let a user download the html page as a file when the user clicks the button. What I imagine is something like saving the rendered html into BytesIO and send it via send_file, but I can’t find how to save the rendered page into a file object. How can I do that?

Asked By: Chan Y. Park

||

Answers:

You could try something like this:

import StringIO
from flask import Flask, send_file, render_template

def page_code():   
    strIO = StringIO.StringIO()
    strIO.write(render_template('hello.html', name='World'))
    strIO.seek(0)
    return send_file(strIO,
                     attachment_filename="testing.txt",
                     as_attachment=True)

It is not tested but should give you an idea.

Answered By: Reto Aebersold

@gtomer Using the input from the thread, I may have figured out a solution that helped eliminate the AssertionError (by using BytesIO since on StringIO) that worked for me. This is on Python39.

xx = asteriod.query.filter_by(order_number=tagVV).first()
yy = toposphere.query.filter_by(order_number=tagVV).all()
            
apple = io.BytesIO()
apple.write(render_template("receipt2.html", x12=yy, x13=ww, x14=xx).encode('utf-8'))
apple.seek(0)
return send_file(apple, attachment_filename="testing.html", as_attachment=True)
Answered By: user15771504
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.