Wednesday, June 15, 2011

Simple Python HTTP Web Server

Installing and loading up Apache is usually overkill for hosting a simple web server. Python provides a built in HTTP server with limited functionality. In its simplest form, the following python script could be run from any directory to give access to the directory contents via HTTP:

import SimpleHTTPServer, SocketServer
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
server = SocketServer.TCPServer(("",80), handler)
server.serve_forever()

Running this server will serve up the process' working directory content to any requesting web browser or http client. Customizing this server to provide dynamic web pages is as easy as subclassing the SimpleHTTPRequestHandler. For example:

import SimpleHTTPServer, SocketServer
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "mypage.html":
            self.wfile.write("<html><body>")             self.wfile.write("Hello World!")             self.wfile.write("</body></html>")
            return
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
handler = MyHandler
server = SocketServer.TCPServer(("",80), handler)
server.serve_forever()

The do_GET method overrides the definition in SimpleHTTPRequestHandler to implement a custom action. The script above will return a page with "Hello world!" in its body if a GET is received for "mypage.html". Any other path will result in a call to the original implementation of do_GET().