从Flask框架编写CSV

时间:2014-11-18 15:16:59

标签: python 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,因为它符合我的目标。

5 个答案:

答案 0 :(得分:57)

我最近做了类似的事情,我发现我需要首先将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

答案 1 :(得分:6)

您需要添加换行符。无论如何,你制作csv的方法(打印列表并从中删除括号)并不是最好的方法。试试这个:

csvList = '\n'.join(','.join(row) for row in csvList)

或使用csv模块:

import io, csv

dest = io.StringIO()
writer = csv.writer(dest)

for row in csvList:
    writer.writerow(row)

# Now dest is a file-like object containing your csv

答案 2 :(得分:4)

一个替代::

from flask import Flask, make_response
import pyexcel as pe
import StringIO # py2.7, for python3, please use import io

app = 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 output

if __name__ == "__main__":
    app.debug=True
    app.run()

另一种方法是使用Flask-Excel:

from flask import Flask, make_response
from flask.ext import excel

app = 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 output

if __name__ == "__main__":
    app.debug=True
    app.run()

答案 3 :(得分:1)

由于csv只是一种纯文本格式,因此您应该确保新行分隔符 - \n出现在您拥有的每一行的末尾

答案 4 :(得分:1)

我不太确定我理解您的目标,但您可以尝试使用str.join()方法。因此,如果您想从列表列表中快速输出CSV:

csvList= [['1', '2', '3'], ['4', '5', '6'], ['asdf', '7', 'eight']]
csvStrings= []
for csvLine in csvList:
    csvStrings += [",".join(csvLine)]
print "\n".join(csvStrings)