如何从csv返回一个生成的行?

时间:2015-06-26 08:52:14

标签: python csv

我希望使用their documentation中共享的方法将大型数组(来自数据库)的结果传递给浏览器(使用Flask):

@app.route('/large.csv')
def generate_large_csv():
    def generate():
        for row in iter_all_rows():
            yield ','.join(row) + '\n'
    return Response(generate(), mimetype='text/csv')

扭曲:我不想自己生成csv(加入',',添加分隔线),我想使用csv包。

现在,我发现只返回一条书写行的唯一方法是执行以下操作:

@app.route('/large.csv')
def generate_large_csv():
    def generate():
        for row in iter_all_rows():
            dest = io.StringIO()
            writer = csv.writer(dest)
            writer.writerow(row)
            yield dest.getvalue()

    return Response(generate(), mimetype='text/csv')

但是要创建一个新的io.StringIO&每行csv.writer似乎都不正确!

我看了一下这个包的documentation,但是我找不到只返回一行的东西。

1 个答案:

答案 0 :(得分:2)

You can to it easily with a custom file object. If you create an object with a write method that simply stores its input and give it to a csv writer, it is done :

class keep_writer:
    def write(self, txt):
        self.txt = txt

@app.route('/large.csv')
def generate_large_csv():
    def generate():
        kw = keep_writer()
        wr = csv.writer(kw)  # add optional configuration for the csv.writer
        for row in iter_all_rows():
            wr.writerow(row)  # just write the row
            yield kw.txt      # and yield the line build by the csv.writer
    return Response(generate(), mimetype='text/csv')