在App Engine(Python)中压缩动态文件

che*_*659 6 python google-app-engine zipfile

无论如何,我可以使用zipfile将动态生成的内容(例如新呈现的html模板)压缩到zip文件中吗?

对于压缩静态内容似乎有一些例子,但是没有用于压缩动态内容的例子.或者,它根本不可能吗?

还有一个问题:是否可以创建一个包含一堆子文件夹的zip文件?

谢谢.

che*_*659 14

工作代码:(对于app引擎:)

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())
Run Code Online (Sandbox Code Playgroud)

再次感谢Schnouki和Ryan.


Sch*_*uki 7

您可以使用以下方法将任何内容添加到zip文件中ZipFile.writestr():

my_data = "<html><body><p>Hello, world!</p></body></html>"
z.writestr("hello.html", my_data)
Run Code Online (Sandbox Code Playgroud)

您还可以使用/(或os.sep)作为分隔符来使用子文件夹:

z.writestr("site/foo/hello/index.html", my_data)
Run Code Online (Sandbox Code Playgroud)