~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_ex1b.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
Here we have a slightly more involved case. The deferred is called back with a
 
11
result. the first callback returns a value, the second callback, however
 
12
raises an exception, which is handled by the errback.
 
13
"""
 
14
 
 
15
 
 
16
class Counter(object):
 
17
    num = 0
 
18
 
 
19
def handleFailure(f):
 
20
    print "errback"
 
21
    print "we got an exception: %s" % (f.getTraceback(),)
 
22
    f.trap(RuntimeError)
 
23
 
 
24
def handleResult(result):
 
25
    Counter.num += 1
 
26
    print "callback %s" % (Counter.num,)
 
27
    print "\tgot result: %s" % (result,)
 
28
    return "yay! handleResult was successful!"
 
29
 
 
30
def failAtHandlingResult(result):
 
31
    Counter.num += 1
 
32
    print "callback %s" % (Counter.num,)
 
33
    print "\tgot result: %s" % (result,)
 
34
    print "\tabout to raise exception"
 
35
    raise RuntimeError, "whoops! we encountered an error"
 
36
 
 
37
 
 
38
def behindTheScenes(result):
 
39
    if not isinstance(result, failure.Failure): # ---- callback
 
40
        try:
 
41
            result = handleResult(result)
 
42
        except:
 
43
            result = failure.Failure()
 
44
    else:                                       # ---- errback
 
45
        pass
 
46
 
 
47
 
 
48
    if not isinstance(result, failure.Failure): # ---- callback
 
49
        try:
 
50
            result = failAtHandlingResult(result)
 
51
        except:
 
52
            result = failure.Failure()
 
53
    else:                                       # ---- errback
 
54
        pass
 
55
 
 
56
 
 
57
    if not isinstance(result, failure.Failure): # ---- callback
 
58
        pass
 
59
    else:                                       # ---- errback
 
60
        try:
 
61
            result = handleFailure(result)
 
62
        except:
 
63
            result = failure.Failure()
 
64
 
 
65
 
 
66
def deferredExample():
 
67
    d = defer.Deferred()
 
68
    d.addCallback(handleResult)
 
69
    d.addCallback(failAtHandlingResult)
 
70
    d.addErrback(handleFailure)
 
71
 
 
72
    d.callback("success")
 
73
 
 
74
 
 
75
if __name__ == '__main__':
 
76
    behindTheScenes("success")
 
77
    print "\n-------------------------------------------------\n"
 
78
    Counter.num = 0
 
79
    deferredExample()