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

# Source Code for Module Products.ZenUtils.Chain

     1  ###########################################################################
     2  #
     3  # This program is part of Zenoss Core, an open source monitoring platform.
     4  # Copyright (C) 2007, Zenoss Inc.
     5  #
     6  # This program is free software; you can redistribute it and/or modify it
     7  # under the terms of the GNU General Public License version 2 as published by
     8  # the Free Software Foundation.
     9  #
    10  # For complete information please visit: http://www.zenoss.com/oss/
    11  #
    12  ###########################################################################
    13  #! /usr/bin/env python
    14
    15  __doc__='''Chain
    16
    17  Chain a series of deferred actions serially.
    18
    19  $Id$
    20  '''
    21
    22  __version__ = "$Revision$"[11:-2]
    23
    24
    25
    26  from twisted.internet import defer
    27
    28 -class Chain:
    29      """Call a function over an interable of data, after each finishes."""
    30
    31 -    def __init__(self, callable, iterable):
    32          self.callable = callable
    33          self.iterable = iterable
    34          self.results = []
    35          self.defer = defer.Deferred()
    36
    37 -    def run(self):
    38          self.next()
    39          return self.defer
    40
    41 -    def next(self):
    42          "run the next step"
    43          try:
    44              next = self.iterable.next()
    45              self.callable(next).addCallbacks(self.success, self.failure)
    46          except StopIteration:
    47              self.defer.callback(self.results)
    48          except Exception, ex:
    49              self.failure(ex)
    50
    51 -    def success(self, result):
    52          "gather a successful result"
    53          self.results.append((True, result))
    54          self.next()
    55
    56 -    def failure(self, result):
    57          "gather an error result"
    58          self.results.append((False, result))
    59          self.next()
    60