From f8efd9312ddbf0d2cf70c0c5c4e12aa8bc69399f Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Wed, 13 Nov 2024 07:42:26 -0800 Subject: [PATCH] Investigate using more precise response --- src/documents/views.py | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/src/documents/views.py b/src/documents/views.py index f98932a6f..dee1abbf1 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -33,6 +33,7 @@ from django.db.models import When from django.db.models.functions import Length from django.db.models.functions import Lower from django.db.models.manager import Manager +from django.http import FileResponse from django.http import Http404 from django.http import HttpResponse from django.http import HttpResponseBadRequest @@ -1595,10 +1596,11 @@ class BulkDownloadView(GenericAPIView): return HttpResponseForbidden("Insufficient permissions") settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True) - temp = tempfile.NamedTemporaryFile( # noqa: SIM115 - dir=settings.SCRATCH_DIR, - suffix="-compressed-archive", - delete=False, + temp_dir = Path( + tempfile.TemporaryDirectory( + dir=settings.SCRATCH_DIR, + delete=False, + ), ) if content == "both": @@ -1608,20 +1610,14 @@ class BulkDownloadView(GenericAPIView): else: strategy_class = ArchiveOnlyStrategy - with zipfile.ZipFile(temp.name, "w", compression) as zipf: + zip_file = temp_dir / "documents.zip" + + with zipfile.ZipFile(zip_file, "w", compression) as zipf: strategy = strategy_class(zipf, follow_filename_format) for document in documents: strategy.add_document(document) - # TODO(stumpylog): Investigate using FileResponse here - with open(temp.name, "rb") as f: - response = HttpResponse(f, content_type="application/zip") - response["Content-Disposition"] = '{}; filename="{}"'.format( - "attachment", - "documents.zip", - ) - - return response + return FileResponse(zip_file.open("rb"), as_attachment=True) class StoragePathViewSet(ModelViewSet, PermissionsAwareDocumentCountMixin):