Python HTTP Server Classes

Python HTTP Server Classes

HTTP Servers- http.server

The http.server module contains classes for implementing HTTP Servers or Web Servers. It is known for implementing basic security checks. The server is accessed mainly through the handler's server instance variable.

Classes - http.server

1. HTTPServer : httpserver.HTTPServer(server_address, RequestHandlerClass)

This is a subclass of TCPServer class and builds on it by storing server address as instance variables namely server_port and server_name.


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

2. ThreadingHTTPServer: httpserver.ThreadingHTTPServer(server_address, RequestHandlerClass)

This class is similar to HTTPServer class but it makes use of threads to handle requests. It proves useful to open web browsers pre-opening sockets, otherwise on which HTTPServer would wait for a very long time.

3. BaseHTTPRequestHandler: httpserver.BaseHTTPRequestHandler( request, client_address,server)

It handles those HTTP requests that arrive at the server. It cannot respond to any actual HTTP request on its own and must ne subclassed to handle each request method. This class provides a number of instance variables and methods for use by subclasses.

4. SimpleHTTPRequestHandler: httpserver.SimpleHTTPRequestHandler(request, client_address,server, directory=None)

This class is used to serve files from the director 'directory' and below, or current directory if 'directory' is unavailable and directly maps the directory structure to HTTP requests.

5. CGIHTTPRequestHandler: httpserver.CGIHTTPRequestHandler( request, client_address,server)

It is either used for serving files or the output of CGI scripts through current directory and below. The mapping of HTTP hierarchical structure to the structure of local directory takes place in the same way as in SimpleHTTPRequestHandler class.

The class attributes, instance variables, methods and implementation of the three variants of RequestHandler Class will be covered in the upcoming articles.