Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 259
Mark Bell Avatar asked Mar 08 '13 07:03

Mark Bell


People also ask

How do I transfer files using SimpleHTTPServer?

Go to the directory with the file you want to share using cd on *nix or MacOS systems or CD for Windows. Start your HTTP server with either python -m SimpleHTTPServer or python3 -m http. server. Open new terminal and type ifconfig on *nix or MacOS or ipconfig on Windows to find your IP address.

What does python SimpleHTTPServer do?

The SimpleHTTPServer module is a Python module that enables a developer to lay the foundation for developing a web server. However, as sysadmins, we can use the module to serve files from a directory. The module loads and serves any files within the directory on port 8000 by default.


1 Answers

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.

like image 116
Francisco Gutiérrez Avatar answered Oct 05 '22 23:10

Francisco Gutiérrez