6

Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile?

There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all?

One more question: Is it possible to create a zip file with a bunch of sub-folders inside it?

Thanks.

3 Answers 3

14

The working code: (for app engine:)

output = StringIO.StringIO()
z = zipfile.ZipFile(output,'w')
my_data = "<html><body><p>Hello, world!</p></body></html>"
z.writestr("hello.html", my_data)
z.close()

self.response.headers["Content-Type"] = "multipart/x-zip"
self.response.headers['Content-Disposition'] = "attachment; filename=test.zip"
self.response.out.write(output.getvalue())

Thanks again to Schnouki and Ryan.

7

You can add whatever you want to a zip file using ZipFile.writestr():

my_data = "<html><body><p>Hello, world!</p></body></html>"
z.writestr("hello.html", my_data)

You can also use sub-folders using / (or os.sep) as a separator:

z.writestr("site/foo/hello/index.html", my_data)
0
3

In addition to Schnouki's excellent answer, you can also pass ZipFile a file-like object, such as one created by StringIO.StringIO.

2
  • If you're using Python 3, it needs to be io.BytesIO (StringIO module is gone, and zipfile expects a bytes buffer) Jun 8, 2009 at 11:36
  • 1
    Oops, just realized that this is about App Engine. You should probably ignore my last comment :), sorry. Jun 8, 2009 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.