python - 如何在不向python文件系统中写入任何内容的情况下压缩或tar静态文件夹? [英] How to zip or tar a static folder without writing anything to the filesystem in python?

查看:19
本文介绍了python - 如何在不向python文件系统中写入任何内容的情况下压缩或tar静态文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题.但是你不能在应用引擎中写入文件系统(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的内容,并将输出写入网页浏览器询问页面(输出永远不会超过 32 Mb).

So basically I need to archive something like/base/naclusing 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.GzipFile() 也支持)更喜欢 gzip 而不是 tarfile)
  • 设置标题以将响应呈现为可下载的文件
  • used StringIO to fake a file in memory
  • used fileobj to pass directly the fake file's object to tarfile.open() (also supported by gzip.GzipFile() if you prefer gzip instead of tarfile)
  • set headers to present the response as a downloadable file

这篇关于python - 如何在不向python文件系统中写入任何内容的情况下压缩或tar静态文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆