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

前端 未结 1 1384
南方客
南方客 2020-12-12 05:57

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 somet

相关标签:
1条回答
  • 2020-12-12 06:53

    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
    0 讨论(0)
提交回复
热议问题