[Twisted-Python] Calling deferred within a callback, good or bad idea ?

Stéphane Brault stephane_brault at yahoo.fr
Sun May 21 12:55:48 MDT 2006


Thanks Thomas,
 I'll try your solution.
 
 Stéphane

----- Message d'origine ----
De : Thomas Hervé <therve at free.fr>
À : Twisted general discussion <twisted-python at twistedmatrix.com>
Envoyé le : Vendredi, 19 Mai 2006, 8h26mn 03s
Objet : Re: [Twisted-Python] Calling deferred within a callback, good or bad idea ?

Selon Stéphane Brault <stephane_brault at yahoo.fr>:

> Hi,
>  I have to call a web service then process the answer, according to the
> answer I may have to call the service again.
>  The traditional way to go would be :
>  condition = 1
>  while condition:
>      message = callWebService()
>      condition = processMessage(message)
>
>  Here is what I do :
>  def function():
>
>      def myCalback(message):
>          condition = processMessage(message)
>          if condition:
>              deferred = callWebService()
>               deferred.addCallback(myCallback)
>
>      deferred = callWebService()
>      deferred.addCallback(myCallback)
>
>  I was wondering if it was the way to go or if there was a better way, since
> I'm not quite sure about the impact of calling new deffered within a
> callback.

You may have a recursion problem with this kind of code (I'm not quite sure when
it happens but it does). One good way is to use deferredGenerator:

# Not tested
def function():
    condition = True
    while condition:
        wfd =  defer.waitForDeferred(callWebService())
        yield wfd
        condition = wfd.getResult()
function = defer.deferredGenerator(function)

--
Thomas

_______________________________________________
Twisted-Python mailing list
Twisted-Python at twistedmatrix.com
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python







More information about the Twisted-Python mailing list