如何在不将任何内容写入python中的文件系统的情况下压缩或压缩静态文件夹? [英] How to zip or tar a static folder without writing anything to the filesystem in python?
本文介绍了如何在不将任何内容写入python中的文件系统的情况下压缩或压缩静态文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我了解这个问题.但是您无法在应用引擎(shutil或zipfile需要创建文件)中写入文件系统.
I know about this question. But you can’t write to filesystem in app engine (shutil or zipfile require creating files).
因此,基本上,我需要使用zip或tar存档类似/base/nacl
的内容,并将输出写入Web浏览器,询问页面(输出永远不会超过32 Mb).
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).
推荐答案
碰巧我今晚不得不解决完全相同的问题:)这对我有用:
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())
要点:
- 使用
StringIO
来伪造内存中的文件 - 使用
fileobj
直接将伪文件的对象传递给tarfile.open()
(如果您更喜欢gzip
而不是tarfile
,则gzip.GzipFile()
也支持) - 设置标题以将响应显示为可下载文件
- 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
这篇关于如何在不将任何内容写入python中的文件系统的情况下压缩或压缩静态文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文