Issue
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?
Solution
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)
Answered By - Robᵩ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.