Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Download a csv file on clicking a button [duplicate]

I just got started with Flask/Python. What I want to achieve is that I have a download button in my HTML and it calls the following function:

function downloadPlotCSV() {         $.ajax({             url: "/getPlotCSV",             type: "post",             success: function(data) {                 dataPlot = JSON.parse(data);                 console.log(dataPlot);             }         });     } 

The incomplete flask code is:

@app.route('/getPlotCSV', methods = ['POST']) def plotCSV():     data = open("outputs/Adjacency.csv") 

The problem I am facing is that I cannot find a way to download this csv file or return it as a JSON string so I can download it using Javascript. Any idea how I can send it as JSON or maybe download it via Flask itself? What's the best way?

like image 686
Tarun Dugar Avatar asked May 04 '15 07:05

Tarun Dugar


People also ask

How do I download a CSV file to click a button with python flask?

Firstly you need to import from flask make_response , that will generate your response and create variable, something like response . Secondly, make response. content_type = "text/csv" Thirdly - return your response.

How do I download multiple files from flask?

In order to offer several files together as a download, you only have the option of compressing them in an archive. In my example, all files that match the specified pattern are listed and compressed in a zip archive. This is written to the memory and sent by the server.


2 Answers

Here is one way to download a CSV file with no Javascript:

#!/usr/bin/python  from flask import Flask, Response app = Flask(__name__)  @app.route("/") def hello():     return '''         <html><body>         Hello. <a href="/getPlotCSV">Click me.</a>         </body></html>         '''  @app.route("/getPlotCSV") def getPlotCSV():     # with open("outputs/Adjacency.csv") as fp:     #     csv = fp.read()     csv = '1,2,3\n4,5,6\n'     return Response(         csv,         mimetype="text/csv",         headers={"Content-disposition":                  "attachment; filename=myplot.csv"})   app.run(debug=True) 
like image 144
Robᵩ Avatar answered Oct 08 '22 17:10

Robᵩ


You can use flask.send_file() to send a static file:

from flask import send_file  @app.route('/getPlotCSV') # this is a job for GET, not POST def plot_csv():     return send_file('outputs/Adjacency.csv',                      mimetype='text/csv',                      attachment_filename='Adjacency.csv',                      as_attachment=True) 
like image 38
kay Avatar answered Oct 08 '22 19:10

kay