How can I serve files with UTF-8 encoding using Python SimpleHTTPServer?

后端 未结 2 556
名媛妹妹
名媛妹妹 2021-02-07 21:35

I often use the following to quickly fire up a web server to serve HTML content from the current folder (for local testing):

python -m SimpleHTTPServer 8000
         


        
2条回答
  •  无人及你
    2021-02-07 22:01

    You can run it with Python scripts too.

    from functools import partial
    from http.server import SimpleHTTPRequestHandler, test
    import os
    
    print('http://localhost:8000/')
    wk_dir = os.getcwd()
    SimpleHTTPRequestHandler.extensions_map = {k: v + ';charset=UTF-8' for k, v in SimpleHTTPRequestHandler.extensions_map.items()}
    test(HandlerClass=partial(SimpleHTTPRequestHandler, directory=wk_dir), port=8000, bind='')
    

    Since test is not in http.server.__all__ so IDE may show a warning, and if you don't want to see it, you can use importlib instead of it. for example:

    import importlib
    http_server = importlib.import_module('http.server')
    http_server.test(HandlerClass=partial(SimpleHTTPRequestHandler, directory=wk_dir), port=8000, bind='')
    

提交回复
热议问题