【问题标题】:Downloading flask-generated html page下载烧瓶生成的 html 页面
【发布时间】:2016-01-31 03:19:01
【问题描述】:

我想在烧瓶生成的网页上放置一个按钮,并在用户单击该按钮时让用户将 html 页面作为文件下载。我想象的是将呈现的html保存到BytesIO并通过send_file发送,但我找不到如何将呈现的页面保存到文件对象中。我该怎么做?

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    你可以试试这样的:

    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 文档没有说明它的返回值,或者我只是错过了它.这样就解决了问题。
    • 这段代码在python3下不起作用。任何想法如何纠正它?
    猜你喜欢
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    相关资源
    最近更新 更多