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

pri*_*stc 2 python django zipfile

我有一个视图,从我的网站获取数据,然后将其变成zip压缩的csv文件.这是我的工作代码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
Run Code Online (Sandbox Code Playgroud)

它很棒.现在我希望在发送之前压缩该文件.这是我被卡住的地方.

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
Run Code Online (Sandbox Code Playgroud)

但那不是它,我不知道如何做到这一点.

Ale*_*lli 5

注意如何,在工作时,你return response...在你返回非工作情况下z,这是不是一个HttpResponse当然的(虽然是应该的!).

所以:使用你的csv_writerNOT response而不是临时文件; 压缩临时文件; 写THAT压缩字节流进response!


pri*_*stc 5

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

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
Run Code Online (Sandbox Code Playgroud)