我正在使用Django的StreamingHttpResponse来动态流式传输一个大型CSV文件。根据文档,需要将一个迭代器传递给响应的
我的问题是:我如何手动在CSV写入器上编写一行数据?手动调用writer.writerow(data)或writer.writeheader()(它也内部调用writerow())似乎并没有写入数据集,而只有来自streaming_content的生成/流式数据被写入输出数据集。
streaming_content
参数:import csv
from django.http import StreamingHttpResponse
def get_headers():
return ['field1', 'field2', 'field3']
def get_data(item):
return {
'field1': item.field1,
'field2': item.field2,
'field3': item.field3,
}
# StreamingHttpResponse requires a File-like class that has a 'write' method
class Echo(object):
def write(self, value):
return value
def get_response(queryset):
writer = csv.DictWriter(Echo(), fieldnames=get_headers())
writer.writeheader() # this line does not work
response = StreamingHttpResponse(
# the iterator
streaming_content=(writer.writerow(get_data(item)) for item in queryset),
content_type='text/csv',
)
response['Content-Disposition'] = 'attachment;filename=items.csv'
return response
我的问题是:我如何手动在CSV写入器上编写一行数据?手动调用writer.writerow(data)或writer.writeheader()(它也内部调用writerow())似乎并没有写入数据集,而只有来自streaming_content的生成/流式数据被写入输出数据集。
yield pseudo_buffer.write(get_headers())
改为:yield pseudo_buffer.writerow(get_headers())
以便在文件的下一行中写入,并避免将['field1','field2','field3']
作为标题写入,而正确的标题应该是'field1','field2','field3'
。 你可以看到pseudo_buffer.write(...)
会直接写入传递的原始参数。 - Reidel