""" PythonHTTPServer.py - simple Web Server using BaseHTTPServer module in Python """ from BaseHTTPServer import HTTPServer from BaseHTTPServer import BaseHTTPRequestHandler import string """ class ourRequestHandler - deals with requests of the Web Server """ class ourRequestHandler(BaseHTTPRequestHandler): """ do_GET helps with GET requests """ def do_GET(self): # always return 200 = OK self.ourPrintCustomHTTPResponse(200) # HTML output self.wfile.write("") self.wfile.write("PythonHTTPServer.py - simple Web Server using BaseHTTPServer module in Python - GET method") self.wfile.write("

Welcome to our simple local Python Web Server.

") self.wfile.write("

Method GET string: " + self.path + "

") # ... browser headers ... self.ourPrintBrowserHeaders() # ... and finish up self.wfile.write("

") """ do_POST helps with POST requests """ def do_POST(self): # always return 200 = OK self.ourPrintCustomHTTPResponse(200) # HTML output self.wfile.write("") self.wfile.write("PythonHTTPServer.py - simple Web Server using BaseHTTPServer module in Python - POST method") self.wfile.write("

") self.ourPrintBrowserHeaders() self.wfile.write("Method Post Data:


") # ... post length logic ... if self.headers.dict.has_key("content-length"): # ... string to int ... our_content_length = string.atoi(self.headers.dict["content-length"]) # ... read from client ... our_raw_post_data = self.rfile.read(our_content_length) self.wfile.write(our_raw_post_data) # ... and finish up self.wfile.write("

") """ ourPrintBrowserHeaders prints HTTP headers """ def ourPrintBrowserHeaders(self): # navigate dictionary header name/value pairs self.wfile.write("Headers:
") our_header_keys = self.headers.dict.keys() for ourkey in our_header_keys: self.wfile.write("" + ourkey + ": ") self.wfile.write(self.headers.dict[ourkey] + "
") """ ourPrintCustomHTTPResponse takes response and sends code and custom headers back to browser """ def ourPrintCustomHTTPResponse(self, ourrespcode): # send back HTTP code self.send_response(ourrespcode) # ... inform ... self.send_header("Content-type", "text/html") # ... describe software ... self.send_header("Server", "ourRequestHandler :-)") # ... close headers self.end_headers() # start server on port 2112 so a URL goes http://localhost:2112/pathtofile ourServer = HTTPServer(('', 2112), ourRequestHandler) # ... loop for 5 requests ... for ourlp in range(5): ourServer.handle_request()