The TemporaryDirectory approach worked fine. I tried generating an 800
MB zip file and serving it for download. The only noticeable thing was
it took a minute to run the zip subcommand on hundreds of files, and
at the end of the download, Firefox's download progress meter delayed
for several seconds before completing it. But these are both due to
the size of the file. Here's an approximation of the Python code:
```
import os
import subprocess
import tempfile
import pyramid.response
def archive(request): # View callable.
tmp_dir = tempfile.TemporaryDirectory()
request.add_finished_callback(cleanup_tmp_dir) # Function defined below.
request.tmp_dir = tmp_dir
tpath =
tmp_dir.name # Path of temporary directory.
zip_filename = "incident-10830.zip"
source_dirname = "incident-10830"
zip_path = os.path.join(tpath, zip_filename)
source_path = os.path.join(tpath. source_dirname)
# ... Set up the source directory ....
command = ["/usr/bin/env", "zip", "r", zip_filename, source_dirname]
# Must chdir to temp directory to run 'zip' to get the archive's
item paths right.
olddir = os.getcwd()
os.chdir(tpath)
try:
subprocess.run(command)
finally:
os.chdir(olddir)
disposition = "attachment; filename=" + zip_filename
response = pyramid.response.FileResponse(zip_path)
response.headers["Content-disposition"] = disposition
return response
def cleanup_tmp_dir(request):
request.tmp_dir.cleanup() # Delete the temp dir and its contents.
# The zip file and its source directory will
```
I used the 'zip' command instead of Python's 'zipfile' module because
my existing script that this view is replacing did, and I don't
remember why. I used 'zipfile' somewhere in another sites. The zip
command does give a nice progress report in the log as it adds each
file and how much it compresses it.
--
Mike Orr <
slugg...@gmail.com>