[Twisted-Python] invoking Deferred synchronously

Phil Mayers p.mayers at imperial.ac.uk
Tue Aug 21 04:33:55 MDT 2007


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.

> 
> 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
>      else:
>          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.





More information about the Twisted-Python mailing list