Search code examples
pythoncherrypyzip

Zip and server multiple in-memory files


I am currently using the code below to generate a word document and then serve this on the web using cherrypy.

tpl.get_docx().save(iostream)
cherrypy.response.headers['Content-Type'] = (
            'application/vnd.openxmlformats-officedocument'
            '.wordprocessingml.document'
            )
cherrypy.response.headers['Content-Disposition'] = (
            'attachment; filename={fname}.docx'.format(
                fname='SP' + kwargs['sp'] + '-'+ kwargs['WO'] + ' ' + kwargs['site'] + ' - ' + 'RPC Report'  +'.docx'
            )
            )
iostream.seek(0)
return file_generator(iostream)

I plan to create more documents, then zip them in-memory and then serve them on the web. how could this be implmented, i have tried using the zipfile library, it seems complicated zipping in-memory files.

the following example i google around may solve my issue, but not sure how to use it.

import zipfile
import StringIO

zipped_file = StringIO.StringIO()
with zipfile.ZipFile(zipped_file, 'w') as zip:
    for i, file in enumerate(files):
        file.seek(0)
        zip.writestr("{}.csv".format(i), file.read())

zipped_file.seek(0)

Solution

  • After hours of persistance, i got this working, yeahhhh

    iostream = BytesIO()
    tpl.get_docx().save(iostream)
    
    iostream1 = BytesIO()
    tpl1.get_docx().save(iostream1)
    
    zip_output = StringIO.StringIO()
    file = zipfile.ZipFile(zip_output, "w")
    file.writestr("test.docx", iostream.getvalue())
    file.writestr("test1.docx", iostream1.getvalue())
    file.close()
    
    cherrypy.response.headers['Content-Type'] = 'application/zip'
    cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="test.zip"'
    
    return zip_output.getvalue()