Streaming a CSV file in Django

后端 未结 3 1690
感动是毒
感动是毒 2020-12-08 05:15

I am attempting to stream a csv file as an attachment download. The CSV files are getting to be 4MB in size or more, and I need a way for the user to actively download the f

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 05:57

    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
    

提交回复
热议问题