下载Flask生成的HTML页面。

5

我希望在由Flask生成的网页上放置一个按钮,让用户在点击按钮后下载该HTML页面。我的想法是将渲染后的HTML保存到BytesIO中,并通过send_file发送该文件,但我找不到如何将渲染后的页面保存到文件对象中。我该怎么做呢?

2个回答

5
你可以尝试像这样做:

您可以尝试类似如下方式:

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)

这并未经过测试,但应该能够给你一个概念。


非常感谢!我没有想到render_template会以字符串形式返回整个HTML页面,我以为它在幕后会做更多的事情,因为API文档没有提到它的返回值,或者我可能错过了。这解决了问题。 - Chan Y. Park
这段代码在 Python3 下无法运行。有什么想法如何纠正它吗? - gtomer
@gtomer,你有没有找到在Python3中解决它的方法?我试图通过运行时下载渲染的HTML模板,但是遇到了这个断言异常:AssertionError: applications must write bytes``` - user15771504
@user15771504 - 不行 - gtomer

0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接