问题
I know about this question. But you can’t write to filesystem in app engine (shutil or zipfile require creating files).
So basically I need to archive something like/base/nacl
using zip or tar, and write the output to the web browser asking the page (the output will never exceed 32 Mb).
回答1:
It just happened that I had to solve the exact same problem tonight :) This worked for me:
import StringIO
import tarfile
fd = StringIO.StringIO()
with tarfile.open(mode="w:gz", fileobj=fd) as tgz:
tgz.add('dir_to_download')
self.response.headers['Content-Type'] ='application/octet-stream'
self.response.headers['Content-Disposition'] = 'attachment; filename="archive.tgz"'
self.response.write(fd.getvalue())
Key points:
- used
StringIO
to fake a file in memory - used
fileobj
to pass directly the fake file's object totarfile.open()
(also supported bygzip.GzipFile()
if you prefergzip
instead oftarfile
) - set headers to present the response as a downloadable file
来源:https://stackoverflow.com/questions/38885764/how-to-zip-or-tar-a-static-folder-without-writing-anything-to-the-filesystem-in