Saturday, September 28, 2013

Python HTTP Web Server

Python makes it extremely simple to create a web server. I adapted the run function provided in the Python documentation to create the following example.

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

run(handler_class=SimpleHTTPRequestHandler)

In the code above, we first import the HTTPServer, BaseHTTPRequestHandler, and SimpleHTTPRequestHandler classes from the http.server module (if you want to know more about modules, look at my slides on Python Modules). We then have a run function that accepts the name of an HTTP server class and an HTTP request handler class as parameters.

The HTTPServer class is used to listen for web requests and dispatch them to request handlers. Request handlers are what we use to figure out what needs to be done and to send a response. The BaseHTTPRequestHandler calls methods with a 'do_' prefix followed by the name of the HTTP action verb (more on that in another post). In the example above, we use a SimpleHTTPRequestHandler that provides the functionality out-of-the-box to serve files from the current directory.

Our example above acts as a glue between the HTTP server and the SimpleHTTPRequestHandler class without doing the actual processing on its own. In another blog post, I will describe how you can create your own request handler class to process requests in Python code.

No comments: