Python Manual Benutzerhandbuch

Seite von 124
Delaying a Response
97
connection. Negotiation of persistent connections between the HTTP client and server is managed by
using special HTTP request and response headers.
Where possible the session manager will undertake to maintain persistent connections without you
needing to take any special actions. This is done as a result of the session manager inserting on your
behalf the special headers as appropriate when you call the "
endHeaders()
" member function.
If the client has requested a persistent connection and supplied a valid content length in the request
headers, and you include a valid content length header in the response headers, the session manager
will aim to maintain the connection. If you do not include a valid content length header in the response
headers, or "
sendError()
" was used to generate a response, the connection will always be shut-
down.
Note that when a HTTP client does send an additional request over the same connection, it will not be
the same HTTP servlet instance that handles the request. Each request received will always be sepa-
rately parsed, with the appropriate HTTP server object and servlet used each time.
Delaying a Response
The servlet framework is implemented on top of the event system. As a result, it is not mandatory that
a complete response be generated by the "
processRequest()
" member function. Instead, the
servlet could execute some action which would result in a callback at a later point in time. When that
callback occurs, then it might complete the response.
class HttpServlet(netsvc.HttpServlet,netsvc.Agent):
def __init__(self,session):
netsvc.HttpServlet.__init__(self,session)
netsvc.Agent.__init__(self)
def processRequest(self):
if self.requestMethod() != "GET":
self.sendError(400)
else:
self.sendResponse(200)
self.sendHeader("Content-Type","text/plain")
self.endHeaders()
self.startTimer(self.completeResponse,10,"timeout")
def completeResponse(self,tag):
self.sendContent("Hi there.")
self.endContent()
This is useful where the servlet needs to wait until data needed to formulate a response is available or
where some form of time dependent server push mechanism is being implemented. Note however that
special steps may be required in these situations to cope with a HTTP client prematurely closing the
connection.