From 482ab6d5ca068d71ea6301f45918946161e9fcc1 Mon Sep 17 00:00:00 2001 From: Lukas Kremla <155779787+lukaskremla@users.noreply.github.com> Date: Thu, 15 Aug 2024 00:02:23 +0200 Subject: [PATCH] Fixed gzip automatic content-type assignment and added automatic compression header configuration (#251) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fixed gzip automatic content-type assignment and added automatic compression setting This implements the fix for detecting the proper content-type even when the file has the ".gz" extension. It further makes sure the compression headers are set properly if a "gz." file is detected, but the compression headers weren't explicitly set by the user. * Added a test for properly auto-determining mime types and setting content encoding header * Modified the gzip file header assignments and following tests according to the feedback. --------- Co-authored-by: Lukáš Kremla --- src/microdot/microdot.py | 5 ++++- tests/files/test.txt.gz | 1 + tests/test_response.py | 11 +++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 tests/files/test.txt.gz diff --git a/src/microdot/microdot.py b/src/microdot/microdot.py index 49128ad..d60f1bb 100644 --- a/src/microdot/microdot.py +++ b/src/microdot/microdot.py @@ -774,7 +774,10 @@ class Response: first. """ if content_type is None: - ext = filename.split('.')[-1] + if compressed and filename.endswith('.gz'): + ext = filename[:-3].split('.')[-1] + else: + ext = filename.split('.')[-1] if ext in Response.types_map: content_type = Response.types_map[ext] else: diff --git a/tests/files/test.txt.gz b/tests/files/test.txt.gz new file mode 100644 index 0000000..1910281 --- /dev/null +++ b/tests/files/test.txt.gz @@ -0,0 +1 @@ +foo \ No newline at end of file diff --git a/tests/test_response.py b/tests/test_response.py index 337f8dc..e27f0a2 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -280,6 +280,17 @@ class TestResponse(unittest.TestCase): 'application/octet-stream') self.assertEqual(res.headers['Content-Encoding'], 'gzip') + def test_send_file_gzip_handling(self): + res = Response.send_file('tests/files/test.txt.gz') + self.assertEqual(res.status_code, 200) + self.assertEqual(res.headers['Content-Type'], + 'application/octet-stream') + + res = Response.send_file('tests/files/test.txt.gz', compressed=True) + self.assertEqual(res.status_code, 200) + self.assertEqual(res.headers['Content-Type'], 'text/plain') + self.assertEqual(res.headers['Content-Encoding'], 'gzip') + def test_default_content_type(self): original_content_type = Response.default_content_type res = Response('foo')