困惑于将CSV文件导入django中的ZIP文件 [英] Confused about making a CSV file into a ZIP file in django

查看:152
本文介绍了困惑于将CSV文件导入django中的ZIP文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看法,从我的网站获取数据,然后使其成为zip压缩的csv文件。这是我的工作代码,不用zip:

I have a view that takes data from my site and then makes it into a zip compressed csv file. Here is my working code sans 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

它的效果很好。现在我想要该文件被压缩后才能发出。这是我被卡住的地方。

and it works great. Now I want that file to be compressed before it gets sent out. This is where I get stuck.

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

但是,我不知道该怎么做。

But thats not it and I have no idea how to do this.

推荐答案

这是我的新功能:

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

这篇关于困惑于将CSV文件导入django中的ZIP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆