SimpleHTTPServer: a quick way to serve a directory

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.




Using 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.


Customizing 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()

Comments

Popular posts from this blog

Steve Lopez and the Importance of Newspapers

Ideas for fixing unconnected computing

Omar to kill me