Search code examples
pythonhtmlflask

Downloading flask-generated html page


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?


Solution

  • 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.