Search code examples
pythonzipcherrypy

Creating a zip file stream in python with Cherry Py?


I would like to create a zip file on the fly to serve to users through Cherry Py: I tried the following code that produced an invalid zip file:

@cherrypy.expose
def ZipDir(self, *args):
    path = "\\".join(args)
    output = StringIO.StringIO()
    file = zipfile.ZipFile(output, "w")

    zip_filename = path + ".zip"

    cherrypy.response.headers['Content-Type'] = 'application/zip'
    cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="%s"' % (zip_filename,)
    dir = filter(lambda x: x.lower().endswith(".mp3") or not ("." in x), os.listdir("G:\\Music\\" + path))
    for f in dir:
        file.write("G:\\Music\\" + path + "\\" + f,f,zipfile.ZIP_DEFLATED)
    return output.getvalue()

The file size looks about right, but it doesnt register as a zip file with any acrhicing applications.


Solution

  • I forgot to call file.close() before the return. That fixed it!