我希望在由Flask生成的网页上放置一个按钮,让用户在点击按钮后下载该HTML页面。我的想法是将渲染后的HTML保存到BytesIO
中,并通过send_file
发送该文件,但我找不到如何将渲染后的页面保存到文件对象中。我该怎么做呢?
您可以尝试类似如下方式:
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)
这并未经过测试,但应该能够给你一个概念。
@gtomer 使用来自线程的输入,我可能已经找到了一个解决方案,帮助消除了AssertionError(通过使用BytesIO代替StringIO),这对我很有效。 这是在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)
render_template
会以字符串形式返回整个HTML页面,我以为它在幕后会做更多的事情,因为API文档没有提到它的返回值,或者我可能错过了。这解决了问题。 - Chan Y. ParkAssertionError: applications must write bytes```
- user15771504