How is zip or tar a static folder without writing anything to the file system in python?

I know about this question . But you cannot write to the file system in the application engine (to work with shutil or zipfile, you need to create files).

So basically I need to archive something like /base/naclusing zip or tar and write the output to a web browser, requesting a page (the output will never exceed 32 MB).

0
source share
1 answer

It so happened that today I had to solve the same problem :) 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 StringIOto fake a file in memory
  • fileobj tarfile.open() ( gzip.GzipFile(), gzip tarfile)
+1

Source: https://habr.com/ru/post/1695350/


All Articles