[Twisted-Python] pb: async call in remote method

Brian Warner warner at lothar.com
Fri Apr 16 18:15:52 EDT 2004

>   def remote_getValue(self, someParam)
>     result = processAsyncRequest(someParam)
>     return notYetReceivedResult
> Is it possible to somehow defer (funny heh) the response that
> remote_getValue should send back to the client until the result from
> processAsyncRequest arrives?

Yes, and in fact a Deferred is precisely what you use to do it. When a
remote_* method returns a Deferred, the PB internals know they should add a
callback to it, and they will refrain from sending a response to the client
until that Deferred fires.

    def remote_getValue(self, someParam):
        d = processAsyncRequest(someParam)
        return d

All you have to do is write your processAsyncRequest() function to create and
return a Deferred, and then do something which fires it with
d.callback(results) when the answer comes back. Maybe something like this:

class RequestHandler:

    def __init__(self):
        self.requests = {}
        self.reqnum = 0

    def processAsyncRequest(self, param):
        reqnum = self.reqnum
        self.reqnum += 1
        d = defer.Deferred()
        self.requests[reqnum] = d
        sendRequest(reqnum, param)  # send query to someone
        # assume our "answerReturned" method is called when they respond
        return d

    def answerReturned(self, reqnum, results):
        d = self.requests[reqnum]
        del self.requests[reqnum]


More information about the Twisted-Python mailing list