From 88a9fc0c4053cbc99dcce6c58b9534f3b0377f58 Mon Sep 17 00:00:00 2001 From: Karl Hobley Date: Wed, 22 Apr 2015 15:37:41 +0100 Subject: [PATCH] Allow backend to be passed in to sendfile() Example: from sendfile import sendfile from sendfile.backends.simple import sendfile as simple_sendfile def myview(request): ... return sendfile(..., backend=simple_sendfile) --- sendfile/__init__.py | 4 ++-- sendfile/tests.py | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/sendfile/__init__.py b/sendfile/__init__.py index da16a83..732c561 100644 --- a/sendfile/__init__.py +++ b/sendfile/__init__.py @@ -32,7 +32,7 @@ def _get_sendfile(): -def sendfile(request, filename, attachment=False, attachment_filename=None, mimetype=None, encoding=None): +def sendfile(request, filename, attachment=False, attachment_filename=None, mimetype=None, encoding=None, backend=None): ''' create a response to send file using backend configured in SENDFILE_BACKEND @@ -48,7 +48,7 @@ def sendfile(request, filename, attachment=False, attachment_filename=None, mime If no mimetype or encoding are specified, then they will be guessed via the filename (using the standard python mimetypes module) ''' - _sendfile = _get_sendfile() + _sendfile = backend or _get_sendfile() if not os.path.exists(filename): from django.http import Http404 diff --git a/sendfile/tests.py b/sendfile/tests.py index 2e68e8b..0da42b9 100644 --- a/sendfile/tests.py +++ b/sendfile/tests.py @@ -87,6 +87,20 @@ def test_attachment_filename_unicode(self): self.assertTrue(response is not None) self.assertEqual('attachment; filename="test\'s.txt"; filename*=UTF-8\'\'test%E2%80%99s.txt', response['Content-Disposition']) + def test_override_backend(self): + def overriden_sendfile(*args, **kwargs): + # Add an extra header to the respone + response = sendfile(*args, **kwargs) + response['X-Backend-Overriden'] = 'yes' + return response + + response = real_sendfile(HttpRequest(), self._get_readme(), backend=overriden_sendfile) + self.assertTrue(response is not None) + self.assertEqual('text/plain', response['Content-Type']) + self.assertEqual(self._get_readme(), smart_str(response.content)) + + self.assertEqual('yes', response['X-Backend-Overriden']) + class TestXSendfileBackend(TempFileTestCase):