How to zip or tar a static folder without writing anything to the filesystem in python?

送分小仙女□ 提交于 2019-11-28 14:37:25

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 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!