gpt4 book ai didi

python - 对在 django 中将 CSV 文件制作成 ZIP 文件感到困惑

转载 作者:行者123 更新时间:2023-11-28 19:51:59 25 4
gpt4 key购买 nike

我有一个 View ,它从我的站点获取数据,然后将其放入一个 zip 压缩的 csv 文件中。这是我的无 zip 工作代码:

def backup_to_csv(request):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=backup.csv'

writer = csv.writer(response, dialect='excel')

#code for writing csv file go here...

return response

而且效果很好。现在我希望该文件在发送之前被压缩。这就是我卡住的地方。

def backup_to_csv(request):

output = StringIO.StringIO() ## temp output file
writer = csv.writer(output, dialect='excel')

#code for writing csv file go here...

response = HttpResponse(mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename=backup.csv.zip'

z = zipfile.ZipFile(response,'w') ## write zip to response
z.writestr("filename.csv", output) ## write csv file to zip

return response

但事实并非如此,我不知道该怎么做。

最佳答案

好的,我知道了。这是我的新功能:

def backup_to_csv(request):

output = StringIO.StringIO() ## temp output file
writer = csv.writer(output, dialect='excel')

#code for writing csv file go here...

response = HttpResponse(mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename=backup.csv.zip'

z = zipfile.ZipFile(response,'w') ## write zip to response
z.writestr("filename.csv", output.getvalue()) ## write csv file to zip

return response

关于python - 对在 django 中将 CSV 文件制作成 ZIP 文件感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1403438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com