在Django中流式处理CSV文件

23 投票
3 回答
20250 浏览
提问于 2025-04-16 12:41

我正在尝试将一个csv文件作为附件下载。现在这些csv文件的大小越来越大,有的甚至超过4MB。我需要一种方法,让用户可以主动下载这些文件,而不必等到所有数据都生成并存储到内存中。

我最开始使用了自己基于Django的FileWrapper类写的文件包装器,但失败了。后来我看到这里有一个方法,使用生成器来流式传输响应:如何用Django流式传输HttpResponse

当我在生成器中抛出错误时,我可以看到我用get_row_data()函数生成了正确的数据,但当我尝试返回响应时,结果却是空的。我还禁用了Django的GZipMiddleware。有没有人知道我哪里出错了?

编辑:我遇到的问题是ConditionalGetMiddleware。我必须替换它,具体代码在下面的回答中。

这是我的视图:

from django.views.decorators.http import condition

@condition(etag_func=None)
def csv_view(request, app_label, model_name):
    """ Based on the filters in the query, return a csv file for the given model """

    #Get the model
    model = models.get_model(app_label, model_name)

    #if there are filters in the query
    if request.method == 'GET':
        #if the query is not empty
        if request.META['QUERY_STRING'] != None:
            keyword_arg_dict = {}
            for key, value in request.GET.items():
                #get the query filters
                keyword_arg_dict[str(key)] = str(value)
            #generate a list of row objects, based on the filters
            objects_list = model.objects.filter(**keyword_arg_dict)
        else:
            #get all the model's objects
            objects_list = model.objects.all()
    else:
        #get all the model's objects
        objects_list = model.objects.all()
    #create the reponse object with a csv mimetype
    response = HttpResponse(
        stream_response_generator(model, objects_list),
        mimetype='text/plain',
        )
    response['Content-Disposition'] = "attachment; filename=foo.csv"
    return response

这是我用来流式传输响应的生成器:

def stream_response_generator(model, objects_list):
    """Streaming function to return data iteratively """
    for row_item in objects_list:
        yield get_row_data(model, row_item)
        time.sleep(1)

这是我创建csv行数据的方法:

def get_row_data(model, row):
    """Get a row of csv data from an object"""
    #Create a temporary csv handle
    csv_handle = cStringIO.StringIO()
    #create the csv output object
    csv_output = csv.writer(csv_handle)
    value_list = [] 
    for field in model._meta.fields:
        #if the field is a related field (ForeignKey, ManyToMany, OneToOne)
        if isinstance(field, RelatedField):
            #get the related model from the field object
            related_model = field.rel.to
            for key in row.__dict__.keys():
                #find the field in the row that matches the related field
                if key.startswith(field.name):
                    #Get the unicode version of the row in the related model, based on the id
                    try:
                        entry = related_model.objects.get(
                            id__exact=int(row.__dict__[key]),
                            )
                    except:
                        pass
                    else:
                        value = entry.__unicode__().encode("utf-8")
                        break
        #if it isn't a related field
        else:
            #get the value of the field
            if isinstance(row.__dict__[field.name], basestring):
                value = row.__dict__[field.name].encode("utf-8")
            else:
                value = row.__dict__[field.name]
        value_list.append(value)
    #add the row of csv values to the csv file
    csv_output.writerow(value_list)
    #Return the string value of the csv output
    return csv_handle.getvalue()

3 个回答

3

我遇到的问题是关于ConditionalGetMiddleware的。我发现django-piston提供了一个替代的中间件,可以用来替代ConditionalGetMiddleware,并且支持流式传输:

from django.middleware.http import ConditionalGetMiddleware

def compat_middleware_factory(klass):
    """
    Class wrapper that only executes `process_response`
    if `streaming` is not set on the `HttpResponse` object.
    Django has a bad habbit of looking at the content,
    which will prematurely exhaust the data source if we're
    using generators or buffers.
    """
    class compatwrapper(klass):
        def process_response(self, req, resp):
            if not hasattr(resp, 'streaming'):
                return klass.process_response(self, req, resp)
            return resp
    return compatwrapper

ConditionalMiddlewareCompatProxy = compat_middleware_factory(ConditionalGetMiddleware)

所以你需要把ConditionalGetMiddleware替换成你的ConditionalMiddlewareCompatProxy中间件,然后在你的视图中(这段代码是从一个聪明的回答中借来的):

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

    #create the reponse object with a csv mimetype
    response = HttpResponse(
        data(),
        mimetype='text/csv',
        )
    #Set the response as an attachment with a filename
    response['Content-Disposition'] = "attachment; filename=test.csv"
    response.streaming = True
    return response
12

从Django 1.5开始,中间件的问题已经解决,并且引入了一个叫做StreamingHttpResponse的新功能。你可以使用下面的代码:

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

关于如何从Django输出CSV文件,有一些文档可以参考,具体内容可以查看这里。不过这些文档没有利用到StreamingHttpResponse,所以我就提交了一个请求来跟踪这个问题

35

这里有一些简单的代码,可以用来处理CSV文件;你可以从这个基础上做你需要的事情:

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

这段代码的意思是把每一行写入一个内存中的文件,然后读取这一行并返回给你。

这个版本在生成大量数据时更高效,但在使用之前一定要先理解上面的内容:

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

撰写回答