Saturday, September 28, 2013

Python: Subclassing the BaseHTTPRequestHandler

As discussed in my previous post, Python provides the HTTPServer class for listening to HTTP requests and dispatching them to request handlers. To write our own handler, we can create a subclass of BaseHTTPRequestHandler and handle the requests by providing functions named with the 'do_' prefix followed by the HTTP action verb (Eg. do_GET, do_HEAD, do_POST etc). The following is an example that uses this approach to create a web server.

from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from http.server import SimpleHTTPRequestHandler

def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
 server_address = ('', 8000)
 httpd = server_class(server_address, handler_class)
 httpd.serve_forever()

class MyHandlerForHTTP(BaseHTTPRequestHandler):
 def do_GET(self):
  self.send_response(200)
  self.send_header('Content-Type', 'text/plain')
  self.end_headers()
  self.wfile.write(bytes('Hello World\n', 'UTF-8'))
  self.wfile.write(bytes('You have requested '+self.path+'\n', 'UTF-8'))

run(handler_class=MyHandlerForHTTP)

In this example, we created a class named MyHandlerForHTTP that inherits from BaseHTTPRequestHandler and defined the do_GET method within it. The BaseHTTPRequestHandler class provides methods to set the HTTP response status code, output the headers, and write data to the response stream. Note that you do not have to call the close method on the wfile member as the BaseHTTPRequestHandler class implicitly calls the flush method of the wfile member after the execution of the do_* method.

No comments: