Skip to content

Commit

Permalink
Refactor MediaTypes (#357)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamchainz committed Feb 6, 2022
1 parent 84d03a3 commit 9fde5e1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
29 changes: 29 additions & 0 deletions tests/test_media_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from __future__ import annotations

from whitenoise.media_types import MediaTypes


def test_matched_filename():
result = MediaTypes().get_type("static/apple-app-site-association")
assert result == "application/pkc7-mime"


def test_matched_filename_cased():
result = MediaTypes().get_type("static/Apple-App-Site-Association")
assert result == "application/pkc7-mime"


def test_matched_extension():
result = MediaTypes().get_type("static/app.js")
assert result == "text/javascript"


def test_unmatched_extension():
result = MediaTypes().get_type("static/app.example-unmatched")
assert result == "application/octet-stream"


def test_extra_types():
types = MediaTypes(extra_types={".js": "application/javascript"})
result = types.get_type("static/app.js")
assert result == "application/javascript"
9 changes: 5 additions & 4 deletions whitenoise/media_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@


class MediaTypes:
def __init__(self, default="application/octet-stream", extra_types=None):
__slots__ = ("types_map",)

def __init__(self, *, extra_types=None):
self.types_map = default_types()
self.default = default
if extra_types:
if extra_types is not None:
self.types_map.update(extra_types)

def get_type(self, path):
Expand All @@ -16,7 +17,7 @@ def get_type(self, path):
if media_type is not None:
return media_type
extension = os.path.splitext(name)[1]
return self.types_map.get(extension, self.default)
return self.types_map.get(extension, "application/octet-stream")


def default_types():
Expand Down

0 comments on commit 9fde5e1

Please sign in to comment.