I have a React application working with a REST backend built into Python and Flask. I download data from a database and save it as a CSV file through a browser. It works for me. However, I donβt understand why I had to go beyond the sources that I read and put together things to make it work. Why didn't I find this outlined better?
Some say that all I need to do is set the response header using mimetype and Content-Disposition: attachment; filename=something.csv Content-Disposition: attachment; filename=something.csv :
However, this in itself worked only with simple links, not fetch() and authentication , so I had to look for ways to save client data to disk, for example:
So my question is:
- Why should I do it this way? or
- What am I missing - which is easier?
It seems that the answer to the first question is that I can not change the request headers (to add an authentication token), except through work like XHR. There seems to be an answer here (no answer):
And that for some reason, answers to XHR with Content-Disposition: attachment do not make sense. It's true? Is there a more modern way to manage such requests in modern browsers?
I feel I donβt understand this enough, and it bothers me.
In any case, here is the working code that I want to simplify, if possible:
JS (Reaction):
Python (Flask):
@app.route("/api/admin/studies/<int:study_id>/csv", methods=["GET"]) @admin.login_required def admin_get_csv(study_id): test = [("1","2","3"),("4","5","6")] def generate(): for row in test: yield ",".join(row) + "\n" return Response( generate() , mimetype="text/csv" , headers={"Content-Disposition": "attachment; filename=study{0}.csv".format(study_id)} )