Writing a CSV from Flask framework [duplicate]
I did something like this recently, I found that I needed to first place the csv into a StringIO and then return the StringIO. If you want the csv to be a download, here's what I did:
import StringIOimport csvfrom flask import make_response@app.route('/download')def post(self): si = StringIO.StringIO() cw = csv.writer(si) cw.writerows(csvList) output = make_response(si.getvalue()) output.headers["Content-Disposition"] = "attachment; filename=export.csv" output.headers["Content-type"] = "text/csv" return output
You need to add newlines. Anyway, your method of making csv
s (printing the list and removing brackets from it) is not the best way to do it. Try this instead:
csvList = '\n'.join(','.join(row) for row in csvList)
Or use the csv
module:
import io, csvdest = io.StringIO()writer = csv.writer(dest)for row in csvList: writer.writerow(row)# Now dest is a file-like object containing your csv
One alternative::
from flask import Flask, make_responseimport pyexcel as peimport StringIO # py2.7, for python3, please use import ioapp = Flask(__name__)data = [ ["REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"], ["1985/01/21","Douglas Adams",'0345391802',5.95], ["1990/01/12","Douglas Hofstadter",'0465026567',9.95], ["1998/07/15","Timothy \"The Parser\" Campbell",'0968411304',18.99], ["1999/12/03","Richard Friedman",'0060630353',5.95], ["2004/10/04","Randel Helms",'0879755725',4.50]]@app.route('/download')def download(): sheet = pe.Sheet(data) io = StringIO.StringIO() sheet.save_to_memory("csv", io) output = make_response(io.getvalue()) output.headers["Content-Disposition"] = "attachment; filename=export.csv" output.headers["Content-type"] = "text/csv" return outputif __name__ == "__main__": app.debug=True app.run()
Another alternative is to use Flask-Excel:
from flask import Flask, make_responsefrom flask.ext import excelapp = Flask(__name__)data = [ ["REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"], ["1985/01/21","Douglas Adams",'0345391802',5.95], ["1990/01/12","Douglas Hofstadter",'0465026567',9.95], ["1998/07/15","Timothy \"The Parser\" Campbell",'0968411304',18.99], ["1999/12/03","Richard Friedman",'0060630353',5.95], ["2004/10/04","Randel Helms",'0879755725',4.50]]@app.route('/download')def download(): output = excel.make_response_from_array(data, 'csv') output.headers["Content-Disposition"] = "attachment; filename=export.csv" output.headers["Content-type"] = "text/csv" return outputif __name__ == "__main__": app.debug=True app.run()