The simplest way to do a download in the way you are asking it to use target="_blank"
on your form:
<form action="/MyPage" method="POST" target="_blank">
<ul>
{% for input in form %}
<li>{{ input.label }} {{ input }}</li>
{% endfor %}
</ul>
</form>
Then your POST
-handling method doesn't need to do anything else but return the 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
If you need multiple buttons on the form, then instead of setting target
on the form, you can just set formtarget="_blank"
on the button that triggers the 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>
Then you just need to add a check for request.form['submit_action']
in your if request.method == 'POST'
block and you're off to the races:
if request.method == 'POST':
if request.form['submit_action'] == 'SAVE_AS_CSV':
# Return the CSV response
else:
# Return the calculation response
See also: Writing a CSV from Flask framework