DEV Community

Gavi Narra
Gavi Narra

Posted on

Custom Mime Type with Python 3 http.server

I needed a quick web server when working with webgpu and needed a custom wgsl mime type.

For this you can just add a mime type the python3 in-built http.server module

import http.server
import socketserver
from urllib.parse import urlparse

# Define the custom MIME types
custom_mime_types = {
    ".wgsl": "text/javascript",
    # Add more custom MIME types here as needed

class CustomMimeTypesHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def guess_type(self, path):
        url = urlparse(path)
        file_ext = url.path
        pos = file_ext.rfind('.')
        if pos != -1:
            file_ext = file_ext[pos:]
            file_ext = ""

        # Check if the file extension has a custom MIME type
        if file_ext in custom_mime_types:
            return custom_mime_types[file_ext]

        # Fallback to the default MIME type guessing
        return super().guess_type(path)

# Set the handler to use the custom class
handler = CustomMimeTypesHTTPRequestHandler

# Set the server address and port
server_address = ("", 4001)

# Create the server and bind the address and handler
httpd = socketserver.TCPServer(server_address, handler)

print(f"Serving on http://{server_address[0]}:{server_address[1]}")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)