[Twisted-Python] help with Deferreds

Terry Jones terry at jon.es
Thu Aug 26 06:17:41 EDT 2010

Hi Sergey

> How to rewrite this regular function with Deferred-style?

Something like the below (untested) will do the job.  You'd have to make
sure that cache.open returned a deferred that fails with NotFound in case
things don't work out.

It would be simpler to translate your code using inlineCallbacks, but it
might be to your advantage to first see how to do it without that.  If you
do take that approach you might want to do some timing tests.



def getCachedResult(cache, key):

    def release(result, item):
        return result

    def renew(data):
        return renew(data)

    def notFound(fail):

    def checkObsolete(item):
        if item.obsolete():
            return None
            d = item.read()
            d.addBoth(release, item)
            return d

    d = cache.open(key)
    d.addCallbacks(checkObsolete, notFound)
    return d

More information about the Twisted-Python mailing list