Re: [Twisted-Python] help with Deferreds

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. Terry --- def getCachedResult(cache, key): def release(result, item): item.release() return result def renew(data): return renew(data) def notFound(fail): fail.trap(NotFound) def checkObsolete(item): if item.obsolete(): return None else: d = item.read() d.addBoth(release, item) d.addCallback(renew) return d d = cache.open(key) d.addCallbacks(checkObsolete, notFound) return d

def getCachedResult(cache, key):
def release(result, item): item.release() return result
def renew(data): return renew(data)
def notFound(fail): fail.trap(NotFound)
def checkObsolete(item): if item.obsolete(): return None else: d = item.read() d.addBoth(release, item) d.addCallback(renew) return d
d = cache.open(key) d.addCallbacks(checkObsolete, notFound) return d
Hi Terry If item.obsolete() raise exception item remain not released. Additional try ... except ... safe us but looks ugly
participants (2)
-
Sergey Magafurov
-
Terry Jones