Package Products :: Package ZenUtils :: Module Chain |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenUtils.Chain

     1  #! /usr/bin/env python
     2  ##############################################################################
     3  #
     4  # Copyright (C) Zenoss, Inc. 2007, all rights reserved.
     5  #
     6  # This content is made available according to terms specified in
     7  # License.zenoss under the directory where your Zenoss product is installed.
     8  #
     9  ##############################################################################
    10
    11
    12  __doc__='''Chain
    13
    14  Chain a series of deferred actions serially.
    15
    16  $Id$
    17  '''
    18
    19  __version__ = "$Revision$"[11:-2]
    20
    21
    22
    23  from twisted.internet import defer
    24
    25 -class Chain:
    26      """Call a function over an interable of data, after each finishes."""
    27
    28 -    def __init__(self, callable, iterable):
    29          self.callable = callable
    30          self.iterable = iterable
    31          self.results = []
    32          self.defer = defer.Deferred()
    33
    34 -    def run(self):
    35          self.next()
    36          return self.defer
    37
    38 -    def next(self):
    39          "run the next step"
    40          try:
    41              next = self.iterable.next()
    42              self.callable(next).addCallbacks(self.success, self.failure)
    43          except StopIteration:
    44              self.defer.callback(self.results)
    45          except Exception, ex:
    46              self.failure(ex)
    47
    48 -    def success(self, result):
    49          "gather a successful result"
    50          self.results.append((True, result))
    51          self.next()
    52
    53 -    def failure(self, result):
    54          "gather an error result"
    55          self.results.append((False, result))
    56          self.next()
    57