在一个Flask响应中返回一个下载和渲染页面 [英] Return a download and rendered page in one Flask response
问题描述
我想返回一个呈现的页面和一个可下载的文件作为对请求的响应。我试图返回这两个响应的元组,但它不起作用。
I want to return a rendered page and a downloadable file as a response to a request. I've tried to return a tuple of both responses, but it doesn't work. How can I serve the download and the page?
return response, render_template('database.html')
return render_template('database.html'), response
Flask能够处理这种情况吗?看起来像一个普遍的问题,我只是想发回一个文件下载,然后呈现该页面。
Is Flask capable of handling such a scenario? Seems like a commonplace problem, I simply want to send a file back for download, then render the page.
推荐答案
您无法返回对单个请求的多个响应。相反,生成和存储文件的地方,并与其他路线。
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)
在模板中,使用 url_for
来生成下载网址。
$ b
In the template, use url_for
to generate the download url.
<a href="{{ url_for('database_download', filename=filename) }}">Download</a>
这篇关于在一个Flask响应中返回一个下载和渲染页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!