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

故事扮演 提交于 2020-01-01 02:56:10

问题


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

Is there a reasonably simple way I can do this, but have the server serve the files with a UTF-8 encoding rather than the system default?


回答1:


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.



来源:https://stackoverflow.com/questions/15288891/how-can-i-serve-files-with-utf-8-encoding-using-python-simplehttpserver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!