[Twisted-Python] help with Deferreds

Tristan Seligmann mithrandi at mithrandi.net
Thu Aug 26 06:38:18 EDT 2010


On Thu, Aug 26, 2010 at 12:23 PM, Sergey Magafurov <smagafurov at naumen.ru> wrote:
> I ask this question because I am confusing with this ugly slice of code:
>
> try:
>     ...
> except:
>     item.release()
>     raise

If you don't like that construct, perhaps this one is nicer:

from twisted.internet.defer import maybeDeferred

def getCachedResult(cache, key):
   def _readItem(item):
       if item.obsolete():
           return None
       return item.read()

   def _gotResult(item):
       def _release(ign):
           item.release()
           return item

       d = maybeDeferred(_readItem, item)
       d.addBoth(_release)
       d.addCallback(renew)
       return d

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

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

-- 
mithrandi, i Ainil en-Balandor, a faer Ambar



More information about the Twisted-Python mailing list