Integrated Web Serving with BaseHTTPServer
These last few days I have been writing a command line reporting program at work. For Linux techs, formatted terminal output works great and is actually their preferred view. However, for managers, you simple must have the eye candy of a GUI. Normally in these situations, I would simply add CGI code and then bundle a simple Apache config to Include along with the code. With this particular program, it could be run on any one of tens of thousands of servers we have, however it is only likely to be run for a short while to graphically review some data stored in JSON files on the server. The overhead of reconfiguring and restarting Apache, even though only a few commands, is probably too much in this particular scenario.
Enter BaseHTTPServer. This includes classes that let your program become the webserver itself, negating the need to run a CGI script or framework under full blown Apache.
1class MyWebServer(BaseHTTPServer.BaseHTTPRequestHandler): 2 3 def do_HEAD(self): 4 self.send_response(200) 5 self.send_header('Content-type', 'text/html') 6 self.end_headers() 7 8 def do_GET(s): 9 try: 10 self.send_response(200) 11 self.send_header('Content-type', 'text/html') 12 self.end_headers() 13 self.wfile.write('<html><head><title>Web Page</title></head>') 14 15 if self.path == '/': 16 self.wfile.write(show_table) 17 else: 18 reportjson='%s/%s' % (rootdir,self.path) 19 self.wfile.write(show_table(self.path)) 20 21 except IOError, e: 22 self.send_error(404,'Oops: %s' % (e)) 23 24 25if __name__ == '__main__': 26 httpd = BaseHTTPServer.HTTPServer(('0.0.0.0',2000),MyWebServer 27 28 try: 29 httpd.serve_forever() 30 31 except KeyboardInterrupt: 32 pass 33 httpd.server_close() 34 35</html>
Now, this obviously isn't going to replace your Apache installation (though I came across bugs in BaseHTTPServer where people were seemingly trying to!) but for development purposes and short lived web serving without affecting the running Apache server on your server, this is a very useful feature I am sure I will be using time and time again.