Skip to content

Commit

Permalink
Merge pull request #78 from Kitware/javascript-mimetypes
Browse files Browse the repository at this point in the history
Ensure javascript files get the correct mimetype
  • Loading branch information
jourdain authored Jun 15, 2022
2 parents 498fd78 + 40a9618 commit 62b9e90
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 62b9e90

Please sign in to comment.