Return a download and rendered page in one Flask response

You cannot return multiple responses to a single request. Instead, generate and store the files somewhere, and serve them with another route. Return your rendered template with a url for the route to serve the file.

@app.route('/database')
def database():
    # generate some file name
    # save the file in the `database_reports` folder used below
    return render_template('database.html', filename=stored_file_name)

@app.route('/database_download/<filename>')
def database_download(filename):
    return send_from_directory('database_reports', filename)

In the template, use url_for to generate the download url.

<a href="https://stackoverflow.com/questions/34009980/{{ url_for("database_download', filename=filename) }}">Download</a>

Leave a Comment