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

后端 未结 2 555
名媛妹妹
名媛妹妹 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:00

    Had the same problem, the following code worked for me.

    To start a SimpleHTTPServer with UTF-8 encoding, simply copy/paste the following in terminal (for Python 2).

    python -c "import SimpleHTTPServer; m = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map; m[''] = 'text/plain'; m.update(dict([(k, v + ';charset=UTF-8') for k, v in m.items()])); SimpleHTTPServer.test();"
    

    Ensure that you have the correct charset in your HTML files beforehand.

    EDIT: Update for Python 3:

    python3 -c "from http.server import test, SimpleHTTPRequestHandler as RH; RH.extensions_map={k:v+';charset=UTF-8' for k,v in RH.extensions_map.items()}; test(RH)"
    

    The test function also accepts arguments like port and bind so that it's possible to specify the address and the port to listen on.

    0 讨论(0)
  • 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='')
    
    0 讨论(0)
提交回复
热议问题