以您要求它在表单上使用的方式进行下载的最简单方法target="_blank"
:
<form action="/MyPage" method="POST" target="_blank">
<ul>
{% for input in form %}
<li>{{ input.label }} {{ input }}</li>
{% endfor %}
</ul>
</form>
然后您的POST
-handling 方法不需要执行任何其他操作,只需返回 CSV:
@app.route('/MyPage', methods=['GET', 'POST'])
def MyPage():
if request.method == 'POST':
# Turn `request.form` into a CSV
# see https://stackoverflow.com/q/26997679/135978 for an example
headers = {'Content-Disposition': 'attachment; filename=saved-form.csv', 'Content-Type': 'text/csv'}
return form_as_csv, headers
else:
# Do some other stuff
如果您需要表单上的多个按钮,那么target
您可以formtarget="_blank"
在触发 CSV 的按钮上设置,而不是在表单上设置:
<form action="/MyPage" method="POST">
<ul><!-- ... snip ... --></ul>
<button name="submit_action" value="SAVE_AS_CSV" formtarget="_blank">Save as CSV</button>
<button name="submit_action" value="RUN_CALCULATION">Run Calculation</button>
</form>
然后你只需要request.form['submit_action']
在你的if request.method == 'POST'
块中添加一个检查,你就可以参加比赛了:
if request.method == 'POST':
if request.form['submit_action'] == 'SAVE_AS_CSV':
# Return the CSV response
else:
# Return the calculation response
另请参阅:从 Flask 框架编写 CSV