Skip to content

Commit

Permalink
Fixed gzip automatic content-type assignment and added automatic comp…
Browse files Browse the repository at this point in the history
…ression 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 <[email protected]>
  • Loading branch information
lukaskremla and Lukáš Kremla authored Aug 14, 2024
1 parent 5fe06f6 commit 482ab6d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/microdot/microdot.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,10 @@ def send_file(cls, filename, status_code=200, content_type=None,
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:
Expand Down
1 change: 1 addition & 0 deletions tests/files/test.txt.gz
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
foo
11 changes: 11 additions & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,17 @@ def test_send_file_compressed(self):
'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')
Expand Down

0 comments on commit 482ab6d

Please sign in to comment.