Jay Taylor's notes

back to listing index

SimpleHTTPServer: a quick way to serve a directory

[web search]
Original source (2ality.com)
Tags: python hacking docker webserver 2ality.com
Clipped on: 2017-10-31

SimpleHTTPServer: a quick way to serve a directory

[2014-06-23] dev, webdev

Python’s SimpleHTTPServer is the classic quick solution for serving the files in a directory via HTTP (often, you’ll access them locally, via localhost). This is useful, because there are some things that don’t work with file: URLs in web browsers.

1Using SimpleHTTPServer  #

SimpleHTTPServer is invoked like this (the parameter <port> is optional):

python -m SimpleHTTPServer <port>

(On OS X, Python is pre-installed and this command works out of the box.)

Let’s look at an example of using SimpleHTTPServer: During the following Unix shell interaction, I first list the files in the current directory and then start SimpleHTTPServer to serve it.

$ ls .
foo.html
$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...

Afterwards, I can access the following URLs:

  • http://localhost:8000/ lists the files in the current directory (namely, just foo.html). If there were a file index.html, it would be displayed, instead.
  • http://localhost:8000/foo.html displays the file foo.html in the current directory.

2Customizing SimpleHTTPServer  #

The following Unix shell script demonstrates how to customize SimpleHTTPServer so that it serves files that have a given file name extension with a given media type. One case where that matters is Firefox being picky about the media type of the webapp.manifest.

#!/usr/bin/python

import SimpleHTTPServer
import SocketServer

PORT = 8000

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
Handler.extensions_map.update({
    '.webapp': 'application/x-web-app-manifest+json',
});

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "Serving at port", PORT
httpd.serve_forever()