【发布时间】:2017-12-04 16:12:52
【问题描述】:
在 Django 视图中,我想在内存中创建一些 csv 文件,然后将它们压缩以下载。
我正在使用 Django 1.11 / Python 2.7。我的代码:
import csv
import zipfile
import StringIO
files = []
csv_buffer = StringIO.StringIO()
writer = csv.writer(csv_buffer)
writer.writerow(["val1", "str1"])
csv_buffer.seek(0)
files.append(csv_buffer)
zipped_file = StringIO.StringIO()
with zipfile.ZipFile(zipped_file, 'w') as zipper:
for i, file in enumerate(files):
file.seek(0)
zipper.writestr("{}.csv".format(i), file.read())
zipped_file.seek(0)
# response = HttpResponse(csv_buffer, content_type='text/csv')
# response['Content-Disposition'] = 'attachment; filename=results.csv'
response = HttpResponse(zipped_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=results.zip'
return response
使用此代码,csv 编码为 utf-8,但我的编辑器抱怨“无效字符”。
如果我只返回 csv 文件,我会得到一个空的 csv。不知道为什么..
我认为 StringIO 缓冲区的编码错误,但我不知道如何使这项工作。如果我这样做:
csv_buffer = StringIO.StringIO("")
我可以创建一个可读的 CSV 文件,但是代码的 zip 部分失败了:
'ascii' codec can't decode byte 0xd4 in position 10: ordinal not in range(128)
任何解释这里出了什么问题将不胜感激!
编辑: 错字 编辑 2: 添加了 zip 错误消息
【问题讨论】:
标签: python django python-2.7 csv