XML technologies / XML / Python & XML / Python’s Internet APIs / Using the server classes

(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)

Now that you understand sockets, you are ready to code your own network servers. Before trying to implement an HTTP server, however, first see which modules Python already offers.

Python provides a basic HTTP server, a simple HTTP server and a CGI HTTP server. The simple server primarily sends files from the local directory to clients requesting them over HTTP. The CGI server is similar, but executes CGI scripts and supplies the environment variables they need to interact with browser clients. The most interesting of all, however, is BaseHTTPServer.

The BaseHTTPServer module contains a simple socket server (the HTTP-Server class) that accepts HTTP requests. You can implement some methods of Base-HTTPRequestHandler to handle the request. These two classes give you considerable power in dealing with clients. Instead of simply returning files or starting external CGI programs, you can interpret URLs however you wish and return anything you want to the client. If you have worked with application servers offering their own inline scripting language (such as PHP, Cold Fusion, Active Server Pages, etc.), you have seen basic HTTP servers in practice. When an application server such as Cold Fusion runs with your web server, the web server passes every HTTP request with the extension .cfm to the Cold Fusion process. The server itself does absolutely nothing with a request marked as a Cold Fusion request. Cold Fusion examines it and sends back the appropriate data after executing any inline code in the file.

In this section we implement a basic HTTP server that handles both GET and POST requests. Because it runs on port 2112, the server handles all HTTP traffic directed to that port, whatever filename is requested. In fact, it returns no files at all, but a standard response for every browser, regardless of the information in the URL.

Classes in the BaseHTTPServer module

The module BaseHTTPServer contains two classes: HTTPServer and BaseHTTPRequestHandler. You will probably only need to learn the four methods of these classes described in this section.

The constructor of the HTTPServer class takes two arguments: an address tuple (hostname and port) and a reference to a request handler. Once instantiated, the HTTPServer class has two operating modes. Call serve_forever to serve an unlimited number of clients, or handle_request to serve one client.

The class BaseHTTPRequestHandler is a placeholder class that you can override for specific functionality. You will probably only override the methods do_GET and do_POST. They are called whenever a new HTTP request arrives asking for a GET or POST operation. A request handler (rh) has several important attributes:

rh.headers
A dictionary of header/value pairs.

rh.rfile
The socket’s request or read file descriptor. It lets you read data beyond the headers into the server, as in a POST operation.

rh.wfile
The socket’s write file descriptor. This attribute lets you send data to the source of the HTTP request, back to the client or browser.

rh.path
The request and path portion of the query string.

rh.command
The requested HTTP request type (GET, POST, HEAD or PUT).

rh.request_version
A string containing the HTTP version currently in use.

rh.client_address
A tuple representing the client address.

Core server concepts

The basic server class has a fairly simple architecture. HTTP headers arrive as a dictionary, and a few simple functions let you write various aspects of an HTTP request back to its sender. At the core are the variables rfile and wfile of the class BaseHTTPRequestHandler. These two objects let you read directly from, and write directly to, the client socket.

Instantiating a server class

To instantiate and start a server, use the HTTPServer constructor. For example:

myServer = HTTPServer(('', 2112), myRequestHandler)
for lp in range(5):
   myServer.handle_request( )

This code tells the server to bind to localhost (using the tuple containing an empty string and a port number) and accept a particular request handler. Besides handle_request, HTTPServer provides the method serve_forever, which never returns. The choice of method is yours. Later in this section, the example HTTPServer.py handles five requests before terminating. Choosing serve_forever assumes that the server will run for a long time. You will then be unable to interrupt it from the command line. If you choose serve_forever, you essentially need to build in a way to stop your server, either by sending a special command over the network or by changing a lock file or another switch in the server’s filesystem. Of course, you can always find and kill the process, using kill -9 under Unix or a quick visit to Task Manager under Windows.

Serving a GET

When implementing a request handler, you must implement do_GET and do_POST. A GET operation is easiest, since most of the information you might need is in the headers.

class myRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):

For newcomers: your request handler (myRequestHandler) must derive from the class BaseHTTPServer.BaseHTTPRequestHandler. After that first step, use some of the methods of HTTPServer to send a response to the user.

self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers( )

After ending the headers with a call to end_headers, use the write file to send data to the browser.

self.wfile.write("<html><body>")
self.wfile.write("<b>Hallo</b>")
self.wfile.write("</html></body>")

The actual requested URI would be available in the request handler’s path attribute (self.path in the previous example). Use this path information to return a particular file or call a particular method of a particular object. The remaining client information from the headers is stored in the header dictionary.

Serving a POST

Implementing a POST operation is somewhat harder and requires knowing how HTTP works during a POST operation. The main difference is that, after reading the browser or client headers, the server must determine how many bytes to read from the client socket for the POST operation. To specify this, every browser POST operation supplies a header named content-length indicating the size of the data.

The basic method calls associated with POST are shown here:

def do_POST(self):    

    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers( )

    self.wfile.write("<html><body>")
    self.printBrowserHeaders( )
    self.wfile.write("<b>Post-Daten:</b><br>")

    if self.headers.dict.has_key("content-length"):

        content_length = string.atoi(self.headers.dict["content-length"])

        raw_post_data = self.rfile.read(content_length)
        self.wfile.write(raw_post_data)

As you can see, the length of the data sent is specified in a header named content-length and transmitted with the remaining client headers. Naturally, the value of content-length must be converted from a string to an integer before use in a read operation on the input file.

Building a complete server

An example is the best way to learn the steps needed to implement your own server. In the example HTTPServer.py, writing the HTTP response and parsing the input headers for HTML output are moved into function calls, giving access to both the do_GET and do_POST methods. The function printBrowserHeaders simply iterates over the browser headers, formats them as HTML, and writes them back over the socket:

def printBrowserHeaders(self):   
   # Iteriere durch Header-Dictionary und
   # zeige Namen und Wert jedes Paares an.
   self.wfile.write("<p>Kopf: <br>")
   header_keys = self.headers.dict.keys( )
   for key in header_keys:
      self.wfile.write("<b>" + key + "</b>: ")
      self.wfile.write(self.headers.dict[key] + "<br>")

The method printCustomHTTPHeaders sends a response code to the browser and ends the HTTP headers. Add any additional headers here.

def printCustomHTTPResponse(self, respcode):

# Sende passenden HTTP-Code zurück
self.send_response(respcode)

# Teile mit, daß wir HTML senden
self.send_header("Content-type", "text/html")

# Beschreibe die verwendete Serversoftware!
self.send_header("Server", "myRequestHandler :-)")

# Beende Header
self.end_headers( )

The following example, HTTPServer.py, gives the complete server listing using the techniques presented so far.

 

Example: HTTPServer.py

"""
HTTPServer.py - eine einfache Implementierung
auf Basis des BaseHTTPServer-Moduls
"""
from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import string
"""
Klasse myRequestHandler - Behandelt alle eingehenden Anfragen,
unabhängig von Pfad, Datei oder Anfragemethode (GET/POST)
"""
class myRequestHandler(BaseHTTPRequestHandler):
"""
do_GET wird aufgerufen, wenn der Browser eine GET-Anfrage stellt.
"""
def do_GET(self):
# Gib immer ein 200/OK zurück
self.printCustomHTTPResponse(200)
# Beginne HTML-Ausgabe
self.wfile.write("<html><body>")
self.wfile.write("<p>Hallo, ich bin eine Art Webserver.</p>")
self.wfile.write("<p>GET-String: " + self.path + "</p>")
# Zeige Browser-Header
self.printBrowserHeaders( )
# Beende HTML
self.wfile.write("</html></body>")
"""
do_POST wird aufgerufen, wenn der Browser Daten aus einem Formular POSTet
"""
def do_POST(self):
# Sende ein 200/OK zurück
self.printCustomHTTPResponse(200)

# Beginne HTML und zeige erneut Browser-Header
self.wfile.write("<html><body>")
self.printBrowserHeaders( )
self.wfile.write("<b>Post-Daten:</b><br>")

# Bestimme Länge der POST-Daten, damit Sie die korrekte Anzahl von Bytes
# einlesen können. Die Länge der POST-Daten ist im Browser-Header
# namens 'content-length' angegeben.
if self.headers.dict.has_key("content-length"):
# Konvertiere content-length von String nach Ganzzahl
content_length = string.atoi(self.headers.dict["content-length"])

# Lies die korrekte Anzahl von Bytes von der Client-Verbindung
# und sende sie zum Browser zurück
raw_post_data = self.rfile.read(content_length)
self.wfile.write(raw_post_data)

# Beende HTML
self.wfile.write("</html></body>")

"""
printBrowserHeaders - diese Methode gibt die vom Client gesendeten HTTP-Header aus
"""
def printBrowserHeaders(self):
# Iteriere durch Header-Dictionary und zeige Namen und Wert jedes Paares an.
self.wfile.write("<p>Kopf: <br>")
header_keys = self.headers.dict.keys( )
for key in header_keys:
self.wfile.write("<b>" + key + "</b>: ")
self.wfile.write(self.headers.dict[key] + "<br>")

"""
printCustomHTTPResponse - diese Methode nimmt einen Antwortcode und
sendet den Code und spezielle Header an den Browser zurück
"""
def printCustomHTTPResponse(self, respcode):

# Sende passenden HTTP-Code zurück
self.send_response(respcode)

# Teile mit, daß wir HTML senden
self.send_header("Content-type", "text/html")

# Beschreibe die verwendete Serversoftware!
self.send_header("Server", "myRequestHandler :-)")

# Beende Header
self.end_headers( )

# Um den Server auf Port 2112 zu starten, müssen die Browser-URLs

# als http://servername:2112/pathtofile adressiert sein
myServer = HTTPServer(('', 2112), myRequestHandler)

# Behandle 5 Anfragen in einer Schleife
for lp in range(5):
   myServer.handle_request( )

Running a GET request

To start your new server, simply invoke Python with its name:

 C:\WINDOWS\Desktop\oreilly\pythonxml\c8>python HTTPServer.py 

The prompt does not return until the server has handled five requests. To test its GET functionality, simply start your browser and enter your server’s name and port 2112 ("http://hostname:2112") to get a response. The path does not matter, since the server ignores it. The following figure shows a browser making a GET request to the server with the URL "http://localhost:2112/this/path/and/pagename/are/made.up?its=true".
The only critical part of the URL is the host:port combination in the form "http://localhost:2112".

A browser connecting to the server with a GET request

Figure: A browser connecting to the server with a GET request

Running a POST request

A POST operation requires a web form. The simple HTML file testServer.html shown in the following example, testServer.html, should suffice. It need not reside on a web server; just load it into your browser like any file. Pressing the submit button makes the form try to send its data using POST to your file HTTPServer.py running on port 2112. The following example shows the markup for testServer.html.

Example: testServer.html

<html>
  <body>
    <form action="http://localhost:2112/dieser/Teil/ist/egal" method="POST">
      <textarea rows=10 cols=40 name="textdata">Diese Beispieldaten kann man abschicken, wenn Sie wollen.</textarea><br>
      <input type="submit" value="Abschicken">
    </form>
  </body>
</html>

The following figure shows the web form from the example testServer.html as displayed by your browser with its default text. Remember that this form’s action attribute must point to port 2112 rather than port 80.

A web form for testing the server

Figure: A web form for testing the server

When the form is submitted, the server ignores the path and filename just as with the GET request, and HTTPServer.py instead simply reads the request data using rfile. The browser sends the content-length header to tell the server how many bytes to try to read from the socket. The following figure shows the server’s response. It resembles the GET response, but your POST data is also present and correctly URL-encoded.

A response to a submitted form

Figure: A response to a submitted form

This section has linked many of Python’s Internet subsystems. When writing applications that use XML in distributed systems, understanding how these subsystems cooperate is important. Knowing how web servers operate, how URLs are encoded and decoded, and how threads and sockets function in network programming enables you to build distributed systems and XML with a more robust toolkit. XML is still a very new technology; using it effectively requires a thorough understanding of its distributed network environment, including protocols, sockets, threads and other APIs. On the following pages we explore web services and SOAP. With Python’s emerging SOAP support, what you have learned here will be particularly useful.

  

 

 

 

back to top