In Flask how can I redirect to a template and show a message after returning send_file in a view?
flask, python
Solution
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())
Problem
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) ```