Confused about creating CSV file to ZIP file in django

I have a view that takes data from my site and then turns it into a zs compressed csv file. Here is my working sans zip code:

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 this file to be compressed before it gets sent. This is where I am 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 it is not, and I have no idea how to do it.

+2


source to share


3 answers


OK, I get it. Here's my new function:



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

      

+5


source


Note that in the work case, you return response

... and in the non-work case, you return z

, which of course is NOT a HttpResponse

(while it should be!).



So: use csv_writer

NOT on response

, but in a temporary file; zip temporary file; and write THAT zipped bytestream in response

!

+5


source


zipfile.ZipFile(response,'w') 

      

doesn't seem to work in python 2.7.9. the answer is a django.HttpResponse object (which is called a file one), but it gives an error: "The HttpResponse object does not have a" look for "attribute. the same code runs in python 2.7.0 or 2.7.6 (I have not tested it in other versions) , that's ok ... So you'd better test it with python 2.7.9 and see if you get the same behavior.

+1


source