且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中流式传输一个CSV文件

更新时间:2023-02-16 12:08:36

这里有一些简单的代码,将流式传输CSV;你可以从这个到你需要做的任何事情:

Here's some simple code that'll stream a CSV; you can probably go from this to whatever you need to do:

import cStringIO as StringIO
import csv

def csv(request):
    def data():
        for i in xrange(10):
            csvfile = StringIO.StringIO()
            csvwriter = csv.writer(csvfile)
            csvwriter.writerow([i,"a","b","c"])
            yield csvfile.getvalue()

    response = HttpResponse(data(), mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=test.csv"
    return response

这只是将每行写入一个内存中的文件,读取该行并生成它。

This simply writes each row to an in-memory file, reads the row and yields it.

此版本更有效地生成批量数据,但请务必在使用之前了解上述内容:

This version is more efficient for generating bulk data, but be sure to understand the above before using it:

import cStringIO as StringIO
import csv

def csv(request):
    csvfile = StringIO.StringIO()
    csvwriter = csv.writer(csvfile)

    def read_and_flush():
        csvfile.seek(0)
        data = csvfile.read()
        csvfile.seek(0)
        csvfile.truncate()
        return data

    def data():
        for i in xrange(10):
            csvwriter.writerow([i,"a","b","c"])
        data = read_and_flush()
        yield data

    response = HttpResponse(data(), mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=test.csv"
    return response