0

I am am creating a web app with Python and Flask. My python code outputs a pandas dataframe, which I would like the user to download by the click of a button. More specifically, I want the user to click the download button and I want the csv file to be displayed as a download on the bottom download bar in Google Chrome (Something like this picture.).

Here's what I did so far:

HTML button:

 <a class="btn btn-primary" onclick="csvDownload()" href=""  type="button">Download</a>

Which leads to this JavaScript function:

 function csvDownload() {
        location.replace('/download')
    }

In Flask, I process it like so:

@app.route('/download')
def download():
   backend.final_data.to_csv()

Here, backend.final_data is my data frame coming from another python file called backend.

DinoMan
  • 35
  • 5
  • this may help you [help1](https://stackoverflow.com/questions/38634862/use-flask-to-convert-a-pandas-dataframe-to-csv-and-serve-a-download) [help2](https://stackoverflow.com/questions/42809592/flask-pandas-creating-a-download-file) [help3](https://gist.github.com/c0ldlimit/5164171), [help4](https://stackoverflow.com/questions/45721350/python-flask-send-file-and-variable) basically from flask side you need to return the text/csv as a file response in download folder – sahasrara62 Apr 20 '20 at 15:40
  • thanks a lot, help1 solved my problem – DinoMan Apr 20 '20 at 16:18
  • yes it does @sahasrara62 – DinoMan Apr 20 '20 at 16:27
  • if solution give by @mutantkeyboard solved your problem also you can accept it – sahasrara62 Apr 20 '20 at 16:29

1 Answers1

0

Well, I don't know how your to_csv() is written, but it should look something like:


def to_csv ():
    path = "/Examples.csv"
    return send_file(path, as_attachment=True)

Notice send_file(path, as_attachment=True)

That way, you won't present the data to the browser, but will rather notify the browser to download the file as attachment.

mutantkeyboard
  • 1,614
  • 1
  • 16
  • 44