如何压缩或 tar 静态文件夹而不向 python 中的文件系统写入任何内容?
How to zip or tar a static folder without writing anything to the filesystem in python?
我知道 this question。但是你不能在 App Engine 中写入文件系统 (shutil 或 zipfile 需要创建文件).
所以基本上我需要使用 zip 或 tar 来归档类似 /base/nacl
的内容,并将输出写入询问页面 的网络浏览器(输出永远不会超过 32 mb).
碰巧我今晚不得不解决完全相同的问题 :) 这对我有用:
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())
要点:
- 使用
StringIO
在内存中伪造一个文件
- 使用
fileobj
将伪造文件的 object 直接传递给 tarfile.open()
(如果您更喜欢 gzip
而不是 [=16,gzip.GzipFile()
也支持=])
- 设置 headers 以将响应显示为可下载文件
我知道 this question。但是你不能在 App Engine 中写入文件系统 (shutil 或 zipfile 需要创建文件).
所以基本上我需要使用 zip 或 tar 来归档类似 /base/nacl
的内容,并将输出写入询问页面 的网络浏览器(输出永远不会超过 32 mb).
碰巧我今晚不得不解决完全相同的问题 :) 这对我有用:
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())
要点:
- 使用
StringIO
在内存中伪造一个文件 - 使用
fileobj
将伪造文件的 object 直接传递给tarfile.open()
(如果您更喜欢gzip
而不是 [=16,gzip.GzipFile()
也支持=]) - 设置 headers 以将响应显示为可下载文件