Fixed gzip automatic content-type assignment and added automatic compression header configuration (#251)

* 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 <lukas.kremla@bonnel.cz>
This commit is contained in:
Lukas Kremla
2024-08-15 00:02:23 +02:00
committed by GitHub
parent 5fe06f6bd5
commit 482ab6d5ca
3 changed files with 16 additions and 1 deletions

View File

@@ -774,6 +774,9 @@ class Response:
first.
"""
if content_type is None:
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]

1
tests/files/test.txt.gz Normal file
View File

@@ -0,0 +1 @@
foo

View File

@@ -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')