I'm diving into Flask for the first time and I'm running into a little problem. I have a page with a form and a bunch of checkboxes. When submitting the form I'm taking the values from all the checkboxes and passing that into a script (which I already had) that basically writes a CSV file.
What I do is that upon submitting the form, the CSV file is created in the background and sent back to the user for download immediately. I got this part working by making my script create the file in memory (using StringIO) and then returning it using Flask's send_file.
What I would like is to also to give the user some feedback after he downloads the file by flashing a message to the template (you could ask why do I want to notify the user if he already downloaded the file - I just want to give him some extra information). However, after my view function returns send_file and presents a download dialog in the browser, the page isn't reloaded so the flash message doesn't get through.
I'm struggling with this: how can I return the file and also show a message to the user? I understand that each request can only have one response, so if I use my one chance with the file download I might need another strategy. Any ideas?
Here's how my "download route" looks like:
@app.route('/process', methods=["POST"])
def process():
error = None
if request.method == 'POST':
# gets all checkbox values
fields = request.form.getlist("field")
# generates my csv file
csv = generate_csv()
if len(fields) != 0:
csv = amxml2csv.xml2csv(xml, *fields)
flash("Extraction succeeded!")
return send_file(data, attachment_filename="newresults.csv", as_attachment=True)
else:
error = "No fields selected!"
return render_template("index.html", error=error)
Flask sends form data to template Flask to send form data to the template we have seen that http method can be specified in the URL rule. Form data received by the trigger function can be collected in the form of a dictionary object and forwarded to the template to render it on the corresponding web page.
If you want your form to submit to a different route you can simply do <form action="{{ url_for('app. login') }}"> . If you just want to put a link to the page use the <a> tag. If you want to process the request and then redirect, just use the redirect function provided by flask.
Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.
Go to browser and type “http://localhost:8000/get-files/<filename with extension>”.
I'm having the same problem here. A halfway solution so far I found is to do
return send_from_directory() and redirect(url_for())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With