一尘不染

从Flask框架编写CSV

flask

我在Flask框架之外编写CSV没问题。但是,当我尝试从Flask编写它时,它会写入CSV,但只能写在一行上。

这是我关注的模板

@app.route('/download')
def download():
    csv = """"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"""
    response = make_response(csv)
    response.headers["Content-Disposition"] = "attachment; filename=books.csv"
    return response

这样可以完美地编写CSV,但是当我尝试使用代码时,会得到一长行。

我的代码:

@app.route('/download')
def post(self):

    # lots of code

    csvList.append([all,my,data,goes,here])

    csvList = str(re.sub('\[|\]','',str(csvList)))  # convert to a string; remove brackets

    response = make_response(csvList)
    response.headers['Content-Disposition'] = "attachment; filename=myCSV.csv"
    return response

我的输出:

Nashville Physician Service Ce,Treasury Specialist,Brentwood,TN,(615) 507-1646,La Petite Academy,Afternoon Teacher Aide,Goodlettsville,TN,(615) 859-2034,Nashville Physician Service Ce,Denial Resolution Specialist,Brentwood,TN,(615) 507-1646

谢谢。

编辑:我几乎尝试了所有答案,并且它们大部分都起作用,但是我选择了vectorfrog,因为它与我要完成的任务相吻合。


阅读 514

收藏
2020-04-06

共1个答案

一尘不染

我最近做了类似的事情,发现我需要先将csv放入StringIO,然后返回StringIO。如果要csv下载,这是我所做的:

import StringIO
import csv
from 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
2020-04-06