~justin-fathomdb/nova/justinsb-openstack-api-volumes

« back to all changes in this revision

Viewing changes to vendor/Twisted-10.0.0/doc/core/howto/listings/deferred/deferred_ex7.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
 
 
3
# Copyright (c) 2009 Twisted Matrix Laboratories.
 
4
# See LICENSE for details.
 
5
 
 
6
from twisted.internet import defer
 
7
from twisted.python import failure, util
 
8
 
 
9
"""
 
10
The deferred callback chain is stateful, and can be executed before
 
11
or after all callbacks have been added to the chain
 
12
"""
 
13
 
 
14
class Counter(object):
 
15
    num = 0
 
16
 
 
17
def handleFailure(f):
 
18
    print "errback"
 
19
    print "we got an exception: %s" % (f.getTraceback(),)
 
20
    f.trap(RuntimeError)
 
21
 
 
22
def handleResult(result):
 
23
    Counter.num += 1
 
24
    print "callback %s" % (Counter.num,)
 
25
    print "\tgot result: %s" % (result,)
 
26
    return "yay! handleResult was successful!"
 
27
 
 
28
def failAtHandlingResult(result):
 
29
    Counter.num += 1
 
30
    print "callback %s" % (Counter.num,)
 
31
    print "\tgot result: %s" % (result,)
 
32
    print "\tabout to raise exception"
 
33
    raise RuntimeError, "whoops! we encountered an error"
 
34
 
 
35
def deferredExample1():
 
36
    # this is another common idiom, since all add* methods
 
37
    # return the deferred instance, you can just chain your
 
38
    # calls to addCallback and addErrback
 
39
 
 
40
    d = defer.Deferred().addCallback(failAtHandlingResult
 
41
                       ).addCallback(handleResult
 
42
                       ).addErrback(handleFailure)
 
43
 
 
44
    d.callback("success")
 
45
 
 
46
def deferredExample2():
 
47
    d = defer.Deferred()
 
48
 
 
49
    d.callback("success")
 
50
 
 
51
    d.addCallback(failAtHandlingResult)
 
52
    d.addCallback(handleResult)
 
53
    d.addErrback(handleFailure)
 
54
 
 
55
 
 
56
if __name__ == '__main__':
 
57
    deferredExample1()
 
58
    print "\n-------------------------------------------------\n"
 
59
    Counter.num = 0
 
60
    deferredExample2()
 
61