Reputation: 579
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?
Upvotes: 5
Views: 3616
Reputation: 16644
You could try something like this:
from io import StringIO
from flask import Flask, send_file, render_template
def page_code():
strIO = 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.
Upvotes: 6
Reputation: 67
@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)
Upvotes: 0