[Twisted-Python] Re: invoking Deferred synchronously
laurie at holoweb.net
Tue Aug 21 07:16:46 EDT 2007
Phil Mayers wrote:
> On Tue, 2007-08-21 at 05:09 -0400, Laurie Harper wrote:
>> I'm sure this is trivial enough, but it has me scratching my head... I
>> need to call a method that returns a Deferred, then block until the
>> deferred completes (or errback's) and return the final result of the
>> deferred call.
> You don't want to do that.
Perhaps once I get more used to Twisted's programming model, I'll stop
tending to ;-)
>> Specifically, something like:
>> r = None, is_ok = None
>> def ok(p): r, is_ok = p, True
>> def fail(e): r, is_ok = e, False
>> cf = pb.PBClientFactory()
>> reactor.connectTCP(host, port, cf)
>> d = cf.login(creds, client=self).addCallbacks(ok, fail)
>> # BLOCK: wait until d has called 'ok' of 'fail'
>> if is_ok:
>> return r
>> raise r
>> If it helps, I'm trying to create a web application (using Nevow) that
>> connects to another Twister service through the Persistence Broker. I'm
>> trying to implement authentication, and so need a way to wait for the PB
>> connection to succeed/fail so I can send the appropriate response to the
>> HTTP request.
> You certainly don't need to do that in a Nevow app. Just do this (I'm
> assuming this is in a data or render method):
> cf = pb.PBClientFactory()
> reactor.connectTCP(host, port, cf)
> return cf.login(creds, client=self)
> Nevow will see you've returned a deferred and wait for it. Much of
> Twisted will do the same. You NEVER want to "wait" for a deferred.
Wow, nice; it never occurred to me to try that :-) That isn't quite what
I'd need, since I want to retrieve the IPresence returned from login()
and store it in the web server (so it can be used to service subsequent
HTTP requests). However, from the experimentation I did earlier with
inlineCallbacks and the like I think I know how to wrap a deferred up
and do what I need.
Thanks for the pointer, I'll give it a try.
More information about the Twisted-Python