Python http.server with charset=utf-8

When I quickly need a local web server, I use python -m http.server: it comes with Python 3 (usually already installed), renders directory indices or index.html when available, and logs requests to the terminal. It’s pretty customizable as well (see python -m http.server --help). Perfect in a pinch, except that it does not set a charset encoding in its HTML Content-Type header, turning touchés into touchés.

The reason is that HTML5 still falls back to the windows-1252 encoding. I could set the charset in the HTML with <meta charset=utf-8>, but that’s not nice when typing out a quick experiment, and redundant in production since every “real” server uses Content-Type: text/html; charset=utf-8 instead of the Content-Type: text/html header http.server uses.

I still like http.server for its ubiquity though. So I looked into modifying the headers. Luckily, the module’s CLI is wrapped in a _main() function which we can call into externally. It uses SimpleHTTPRequestHandler to handle the requests, which determines its content-type in guess_type(). So if we replace http.server.SimpleHTTPRequestHandler’s class definition (which many languages would not allow, but in Python stuff like this is fair game) with a subclass modifying guess_type(), we can replace text/html with text/html; charset=utf-8.

#!/usr/bin/env python3
import http.server

class Handler(http.server.SimpleHTTPRequestHandler):
    def guess_type(self, path):
        type = super().guess_type(path)
        if type == "text/html":
            type += "; charset=utf-8"
        return type
http.server.SimpleHTTPRequestHandler = Handler
http.server._main()

This preserves the usual command line interface of http.server (try saving this to serve.py and running ./serve.py --help). To make it even kludgier, you can set default values for http.server arguments like so:

import sys
http.server._main(args=["-d", "public"] + sys.argv[1:])

All because of the magic of Python’s intended lack of privacy / encapsulation (combined with friendly standard library writing practices of the CPython developers). Today, I’m a fan.