[Twisted-Python] help with Deferreds

Tristan Seligmann mithrandi at mithrandi.net
Thu Aug 26 06:04:55 EDT 2010


On Thu, Aug 26, 2010 at 11:47 AM, Sergey Magafurov <smagafurov at naumen.ru> wrote:
> How to rewrite this regular function with Deferred-style?

> Conditions:
> 1. 'cache.open' and 'item.read' become deffered
> 2. 'item.obsolete()' and 'renew(data)' are not deferred

I would probably write it something like this:

def getCachedResult(cache, key):
    def _gotResult(item):
        try:
            if item.obsolete():
                return None
            d = item.read()
            d.addCallback(lambda data: renew(data))
        except:
            item.release()
            raise
        d.addBoth(lambda ign: item.release())
        return d

    def _ebNotFound(f):
        f.trap(NotFound)
        return None

    return cache.open(key).addCallbacks(_gotResult, _ebNotFound)

Note: code is untested
-- 
mithrandi, i Ainil en-Balandor, a faer Ambar



More information about the Twisted-Python mailing list