Skip to content

Commit 482ab6d

Browse files
lukaskremlaLukáš Kremla
andauthored
Fixed gzip automatic content-type assignment and added automatic compression header configuration (miguelgrinberg#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 <[email protected]>
1 parent 5fe06f6 commit 482ab6d

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

src/microdot/microdot.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,10 @@ def send_file(cls, filename, status_code=200, content_type=None,
774774
first.
775775
"""
776776
if content_type is None:
777-
ext = filename.split('.')[-1]
777+
if compressed and filename.endswith('.gz'):
778+
ext = filename[:-3].split('.')[-1]
779+
else:
780+
ext = filename.split('.')[-1]
778781
if ext in Response.types_map:
779782
content_type = Response.types_map[ext]
780783
else:

tests/files/test.txt.gz

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
foo

tests/test_response.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,17 @@ def test_send_file_compressed(self):
280280
'application/octet-stream')
281281
self.assertEqual(res.headers['Content-Encoding'], 'gzip')
282282

283+
def test_send_file_gzip_handling(self):
284+
res = Response.send_file('tests/files/test.txt.gz')
285+
self.assertEqual(res.status_code, 200)
286+
self.assertEqual(res.headers['Content-Type'],
287+
'application/octet-stream')
288+
289+
res = Response.send_file('tests/files/test.txt.gz', compressed=True)
290+
self.assertEqual(res.status_code, 200)
291+
self.assertEqual(res.headers['Content-Type'], 'text/plain')
292+
self.assertEqual(res.headers['Content-Encoding'], 'gzip')
293+
283294
def test_default_content_type(self):
284295
original_content_type = Response.default_content_type
285296
res = Response('foo')

0 commit comments

Comments
 (0)