Skip to content

Commit

Permalink
Use a FileResponse when serving files
Browse files Browse the repository at this point in the history
  • Loading branch information
kevincarrogan committed Feb 5, 2024
1 parent 5f8a0c3 commit 0b0d8b2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
15 changes: 7 additions & 8 deletions api/documents/libraries/s3_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from botocore.exceptions import BotoCoreError, ReadTimeoutError

from django.conf import settings
from django.http import StreamingHttpResponse
from django.http import FileResponse


_client = None
Expand Down Expand Up @@ -68,16 +68,15 @@ def delete_file(document_id, s3_key):
)


def _stream_file(result):
for chunk in iter(lambda: result["Body"].read(settings.STREAMING_CHUNK_SIZE), b""):
yield chunk


def document_download_stream(document):
s3_response = get_object(document.id, document.s3_key)
content_type = mimetypes.MimeTypes().guess_type(document.name)[0]

response = StreamingHttpResponse(streaming_content=_stream_file(s3_response), content_type=content_type)
response["Content-Disposition"] = f'attachment; filename="{document.name}"'
response = FileResponse(
s3_response["Body"],
as_attachment=True,
filename=document.name,
)
response["Content-Type"] = content_type

return response
4 changes: 2 additions & 2 deletions api/documents/libraries/tests/test_s3_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from moto import mock_aws

from django.conf import settings
from django.http import StreamingHttpResponse
from django.http import FileResponse
from django.test import override_settings, SimpleTestCase

from ..s3_operations import (
Expand Down Expand Up @@ -154,7 +154,7 @@ def test_document_download_stream(self):

response = document_download_stream(mock_document)

self.assertIsInstance(response, StreamingHttpResponse)
self.assertIsInstance(response, FileResponse)
self.assertEqual(response.status_code, 200)
self.assertEqual(response["Content-Type"], "application/msword")
self.assertEqual(response["Content-Disposition"], 'attachment; filename="test.doc"')
Expand Down

0 comments on commit 0b0d8b2

Please sign in to comment.