pythonsimplehttpserversimplehttprequesthandler

Add Content-Type header to Very simple SimpleHTTPRequestHandler without extending the class


I have an extremely simple http server setup for local testing:

#!/usr/bin/env python
from functools import partial
from http.server import SimpleHTTPRequestHandler, test
import os

HTTP_DIR = os.getcwd()
SimpleHTTPRequestHandler.extensions_map = {k: v + ';charset=UTF-8' for k, v in SimpleHTTPRequestHandler.extensions_map.items()}

test(HandlerClass=partial(SimpleHTTPRequestHandler, directory=HTTP_DIR), port=8000, bind='0.0.0.0')

I note that the Content-Type header is not sent for css files, and a little further digging indicated to me that it might be something to do with SimpleHTTPRequestHandler.extensions_map but as I understand it, this only has overrides for the system mappings so I assumed that the System mappings should be automatically set?

Changed in version 3.9: This dictionary is no longer filled with the default system mappings, but only contains overrides.

As I understand it, the system defaults should be added automatically, but the dump of print(SimpleHTTPRequestHandler.extensions_map.items()) is this list:

dict_items([('.gz', 'application/gzip;charset=UTF-8'), ('.Z', 'application/octet-stream;charset=UTF-8'), ('.bz2', 'application/x-bzip2;charset=UTF-8'), ('.xz', 'application/x-xz;charset=UTF-8')])

I do see that I could extend the functionality and add custom endpoints, but that would make the implementation more extensive than desired...

EDIT

For some reason .js files do get application/javascript


Solution

  • I added

    SimpleHTTPRequestHandler.extensions_map['.css'] = 'text/css'

    #!/usr/bin/env python
    from functools import partial
    from http.server import SimpleHTTPRequestHandler, test
    import os
    
    HTTP_DIR = os.getcwd()
    SimpleHTTPRequestHandler.extensions_map = {k: v + ';charset=UTF-8' for k, v in SimpleHTTPRequestHandler.extensions_map.items()}
    
    #Custom Content-type
    SimpleHTTPRequestHandler.extensions_map['.css'] = 'text/css'
    test(HandlerClass=partial(SimpleHTTPRequestHandler, directory=HTTP_DIR), port=8000, bind='0.0.0.0')