Search code examples
pythondjangozipstringio

Django response that contains a zip file with multiple csv files


I have a algorithm that outputs a list of tuples which is ready to be written into a csv file.

I'm trying to write 3 csv files (through StringIO so no writing to disk) and then zip them altogether. After that I want to attach that to the response of a django request.

I'm not sure what's the most efficient way to do this. Should I use StringIO to store the 3 calls through my algo? Should I actually create the csv files first before zipping them? Can I directly use 1 zipfile call without the intermediate steps of calling 3 StringIOs?

Thanks


Solution

  • You can do something like:

    # Create the zip file
    output = StringIO.StringIO()
    f = zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED)
    f.writestr('first.csv', '<the content of first.csv>')
    f.writestr('second.csv', '<the content of second.csv>')
    f.writestr('third.csv', '<the content of third.csv>')
    f.close()
    # Build your response
    response = HttpResponse(output.getvalue(), mimetype='application/zip')
    response['Content-Disposition'] = 'attachment; filename="yourzipfilename.zip"'
    return response
    

    You may want to use a StreamingHttpResponse(or FileResponse ) if the file is big https://stackoverflow.com/a/48949959/1904584