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