3
# Copyright (c) 2009 Twisted Matrix Laboratories.
4
# See LICENSE for details.
6
from twisted.internet import defer
7
from twisted.python import failure, util
10
Now comes the more nuanced addCallbacks, which allows us to make a
11
yes/no (branching) decision based on whether the result at a given point is
15
class Counter(object):
21
print "we got an exception: %s" % (f.getTraceback(),)
23
return "okay, continue on"
25
def handleResult(result):
27
print "callback %s" % (Counter.num,)
28
print "\tgot result: %s" % (result,)
29
return "yay! handleResult was successful!"
31
def failAtHandlingResult(result):
33
print "callback %s" % (Counter.num,)
34
print "\tgot result: %s" % (result,)
35
print "\tabout to raise exception"
36
raise RuntimeError, "whoops! we encountered an error"
38
def yesDecision(result):
40
print "yes decision %s" % (Counter.num,)
41
print "\twasn't a failure, so we can plow ahead"
44
def noDecision(result):
46
result.trap(RuntimeError)
47
print "no decision %s" % (Counter.num,)
48
print "\t*doh*! a failure! quick! damage control!"
49
return "damage control successful!"
53
def behindTheScenes(result):
55
if not isinstance(result, failure.Failure): # ---- callback
57
result = failAtHandlingResult(result)
59
result = failure.Failure()
64
# this is equivalent to addCallbacks(yesDecision, noDecision)
66
if not isinstance(result, failure.Failure): # ---- callback
68
result = yesDecision(result)
70
result = failure.Failure()
73
result = noDecision(result)
75
result = failure.Failure()
78
if not isinstance(result, failure.Failure): # ---- callback
80
result = handleResult(result)
82
result = failure.Failure()
87
# this is equivalent to addCallbacks(yesDecision, noDecision)
89
if not isinstance(result, failure.Failure): # ---- callback
91
result = yesDecision(result)
93
result = failure.Failure()
96
result = noDecision(result)
98
result = failure.Failure()
101
if not isinstance(result, failure.Failure): # ---- callback
103
result = handleResult(result)
105
result = failure.Failure()
110
if not isinstance(result, failure.Failure): # ---- callback
114
result = handleFailure(result)
116
result = failure.Failure()
119
def deferredExample():
121
d.addCallback(failAtHandlingResult)
122
d.addCallbacks(yesDecision, noDecision) # noDecision will be called
123
d.addCallback(handleResult) # - A -
124
d.addCallbacks(yesDecision, noDecision) # yesDecision will be called
125
d.addCallback(handleResult)
126
d.addErrback(handleFailure)
128
d.callback("success")
131
if __name__ == '__main__':
132
behindTheScenes("success")
133
print "\n-------------------------------------------------\n"