Python Manual User Manual

Page of 124
Servlet Objects
96
if self.requestMethod() != "GET":
self.sendError(400)
else:
self.sendResponse(200)
self.sendHeader("Content-Type","text/plain")
self.endHeaders()
self.sendContent("Hi there.")
self.endContent()
The major member functions of the HTTP servlet class used to interrogate the details of the HTTP re-
quest are "
requestMethod()
", "
requestPath()
" and "
queryString()
". It is these meth-
ods you would use to determine what the HTTP servlet is to do. It may be the case however that it is
only necessary to validate the type of request method. This would occur where the HTTP server object
had already identified a resource against which a request was being made and supplied the handle for
that resource when the HTTP servlet was created.
Having determined the validity or otherwise of a request, the HTTP servlet can do a number of things.
In the event of an error the HTTP servlet can use the "
sendError()
" member function to generate
an error response. The first argument to "
sendError()
" should be the appropriate HTTP response
code. An optional second argument may also be supplied consisting of valid HTML text. This text will
be included within the body of the HTML document generated by the "
sendError()
" member
function.
If the request is valid, the HTTP servlet might instead generate its own response including any appro-
priate content. To start the response the "
sendResponse()
" member function must be called. The
first argument to "
sendResponse()
" would typically be be "
200
", indicating a successful re-
sponse. A HTTP servlet may if it wishes supply any valid HTTP response code here. In fact, the
"
sendError()
" member function is merely a shorthand method for generating an error response and
underneath actually uses the same functions as described here.
The HTTP servlet may now include any HTTP headers by calling "
sendHeader()
". The arguments
to "
sendHeader()
" should be the name of the header and its string value. Whether or not any HTTP
headers are included, the member function "
endHeaders()
" must now be called.
To include content in a response the "
sendContent()
" member function is used. This may be
called multiple times. When all content has been sent, the "
endContent()
" member function should
be called. Calling the "
endContent()
" member function will have the affect of closing off the re-
sponse and once the "
processRequest()
" member function returns, the servlet will able to be de-
stroyed.
Persistent Connections
A persistent connection is one whereby the connection to the client can be maintained after a response
has been sent. This allows a HTTP client to submit additional requests without the need to create a new