Python Manual User Manual

Page of 124
Delaying a Response
67
When the member function "
suspendResponse()
" is called, a callback function should be sup-
plied as argument which finalises the request and returns the appropriate result. The callback passed
to "
suspendResponse()
" will only be called when the "
resumeResponse()
" method is called
at some later point in time. In particular, you would call "
resumeResponse()
" once you have col-
lected together all the data which forms the result for the original request.
class DatabaseProxy(netsvc.Service):
def __init__(self,name="database-proxy")
netsvc.Service.__init__(self,name):
self.exportMethod(self.tablesRequest,"tables")
self._request = {}
self._result = {}
def tablesRequest(self):
service = self.serviceEndPoint("database")
id = service.execute("show tables")
self.processResponse(self.queryResponse,id)
self.processFailure(self,queryFailure,id)
self._request[id] = self.conversationId()
self.suspendResponse(self.tablesResult)
def tablesResult(self):
request = self.conversationId()
result = self._result[request]
del self._result[request]
return result
def queryResponse(self,id,result):
if self._request.has_key(id):
request = self._request[id]
self._result[request] = result
del self._request[id]
self.resumeResponse(request)
def queryFailure(self,id,error,description,origin,details):
if self._request.has_key(id):
request = self._request[id]
del self._request[id]
self.cancelResponse(request,error,description,origin,failure)
As can be seen, it will be necessary to save away state information about a suspended request so it can
be later resumed. In this example the conversation id of the original request is associated with the con-
versation id of the downstream request. When the result of the downstream request is received, it can
be saved away and the original request resumed with the cached result being returned. In the event that
the downstream request fails, the "
cancelResponse()
" method is used to abort the original re-
quest.
As with the "
abortResponse()
" member function, if "
suspendResponse()
" is being called
from within a method, it will be necessary for any code to be explicit about what exceptions it catches,
or to at least catch the
DelayedResponse
exception and pass it on as is.