[Twisted-Python] How to force synchronous behavior

Stefan Behnel behnel_ml at gkec.informatik.tu-darmstadt.de
Mon Oct 31 08:25:13 MST 2005


Pedro Sanchez schrieb:
> I tried this already and couldn't make it work. In one of the functions
> called during the validation process I have this
> 
>     def registerSession(self, session):
>         def _customerInit(self, customer):
>            ...
>            session.customerInit = True
>
>         # initialize customer data
>         d = defer.Deferred()
>         d1 = defer.maybeDeferred(customerInit, session)
>         d1.addCallback(_customerInit)
>         d1.addErrback(errhandler, session)
>         d.chainDeferred(d1)
>         return d

Ah, there we go. This simplifies to

     def registerSession(self, session):
         def _customerInit(self, customer):
            ...
            session.customerInit = True

         # initialize customer data
         d1 = defer.maybeDeferred(customerInit, session)
         d1.addCallback(_customerInit)
         d1.addErrback(errhandler, session)
         return d1

And then everyone who calls registerSession() receives a Deferred and can add
callbacks for whatever else needs to be done after the session is successfully
registered and _customerInit has been run. You get the difference? The
registration is not done when registerSession /returns/, but when the Deferred
that it returns /fires/. So keep adding callbacks to that Deferred instead of
expecting things to have terminated. Twisted will then take care of running
everything in a chain.

Stefan




More information about the Twisted-Python mailing list