Skip to content

Commit

Permalink
fix(mimetypes): ensure javascript files get the correct mimetype
Browse files Browse the repository at this point in the history
On Windows, the mimetypes are obtained from the registry. However,
the mimetype for javascript files is broken. Add some code to ensure
that javascript files are identified correctly.

This also adds some infrastructure for adding extra mimetypes that
persist even if `mimetypes.init()` is called.

Signed-off-by: Patrick Avery <[email protected]>
  • Loading branch information
psavery committed Jun 15, 2022
1 parent 498fd78 commit 40a9618
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 15 deletions.
3 changes: 3 additions & 0 deletions trame/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
from trame_client import module
from trame_client.widgets.core import VirtualNode

# Ensure this is imported so that mimetypes.init() is decorated
import trame.app.mimetypes # noqa: F401

DEFAULT_NAME = "trame"
AVAILABLE_SERVERS = {}

Expand Down
57 changes: 57 additions & 0 deletions trame/app/mimetypes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import mimetypes


MIMETYPE_OVERRIDES = {
# On Windows, mimetypes pulls this from the registry, which is
# wrong. Override it.
"application/javascript": ".js",
}


def decorate_mimetypes_init():
"""
Decorate the mimetypes.init() method with our function that
afterwards adds any mimetype overrides that were saved.
"""

original_init = mimetypes.init

def new_init(*args, **kwargs):
original_init(*args, **kwargs)
for key, value in MIMETYPE_OVERRIDES.items():
mimetypes.add_type(key, value)

mimetypes.init = new_init


def add_mimetype_override(type, ext):
"""
Add a mimetype both now and when mimetypes.init() is called.
:param type: mimetype
:type type: str
:param ext: file extension for which the mimetype applies
:type ext: str
"""
# Add it to the overrides that are performed if init() is called
MIMETYPE_OVERRIDES[type] = ext

# Also override it right now
mimetypes.add_type(type, ext)


def to_mime(file_path):
"""
Return the mime type from a given path
:param file_path: Path to analyse
:type file_path: str
:return: Mime type
:rtype: str
"""
return mimetypes.guess_type(file_path)[0]


# Decorate the mimetypes.init() method
decorate_mimetypes_init()
16 changes: 1 addition & 15 deletions trame/assets/local.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,7 @@
import base64
import mimetypes
from pathlib import Path

mimetypes.init()


def to_mime(file_path):
"""
Return the mime type from a given path
:param file_path: Path to analyse
:type file_path: str
:return: Mime type
:rtype: str
"""
return mimetypes.guess_type(file_path)[0]
from trame.app.mimetypes import to_mime


def to_txt(full_path):
Expand Down

0 comments on commit 40a9618

Please sign in to comment.