[Twisted-Python] Re: parallel callbacks? Or inserting into the callback chain?

Lenny G Arbage alengarbage at yahoo.com
Sat Jan 28 00:54:54 EST 2006

Okay, I think I figured it out.  The idea is to create
new Deferreds for each call, but keep the 'matching'
ones in a list.  Then, when the first fires, use it to
fire callbacks for each of those:

from twisted.internet import reactor, defer

pending = {}
waiting = {}

def getDummyData(queryName, x):

    def serviceWaiting(res, x):
        #print "in saveResult"
        if waiting.has_key(x):
            #print "waiting has_key"
            for i in waiting[x]:
                #print "calling back with %s on %s" %
(res, i)
        #print "pending now: %s" % pending
        #print "waiting now: %s" % waiting
        return res

    if pending.has_key(x):
        print "%s piggybacking on pending big
expensive query" % queryName
        d = defer.Deferred()
        if not waiting.has_key(x):
            waiting[x] = []
        #print "returning %s" % d
        return d

    d = defer.Deferred()
    # simulate a delayed result by asking the reactor
to fire the
    # Deferred in 2 seconds time with the result x*3
    print "%s about to do some big expensive query" %
    reactor.callLater(2, d.callback, x*3)
    pending[x] = d
    d.addCallback(serviceWaiting, x)   # addBoth() may
be a better choice
    return d

def printData(d, queryName):
    Data handling function to be added as a callback:
handles the
    data by printing the result
    print "%s received: %s" % (queryName, d)

d = getDummyData('query1',3)
d = getDummyData('query2',3)

# manually set up the end of the process by asking the
reactor to
# stop itself in 13 seconds time
reactor.callLater(4, reactor.stop)
# start up the Twisted reactor (event loop handler)

I was making it harder than it needed to be.

Lenny G.

Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 

More information about the Twisted-Python mailing list