Streaming a CSV file in Django

后端 未结 3 1691
感动是毒
感动是毒 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:55

    The middleware issue has been solved as of Django 1.5 and a StreamingHttpResponse has been introduced. The following should do:

    import cStringIO as StringIO
    import csv
    
    def csv_view(request):
        ...
        # Assume `rows` is an iterator or lists
        def stream():
            buffer_ = StringIO.StringIO()
            writer = csv.writer(buffer_)
            for row in rows:
                writer.writerow(row)
                buffer_.seek(0)
                data = buffer_.read()
                buffer_.seek(0)
                buffer_.truncate()
                yield data
        response = StreamingHttpResponse(
            stream(), content_type='text/csv'
        )
        disposition = "attachment; filename=file.csv"
        response['Content-Disposition'] = disposition
        return response
    

    There's some documentation on how to output csv from Django but it doesn't take advantage of the StreamingHttpResponse so I went ahead and opened a ticket in order to track it.

提交回复
热议问题