Debian Codegraph @

docs/core/examples/longex2.py

raw
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 Example of doing arbitrarily long calculations nicely in Twisted.
6
7 This is also a simple demonstration of twisted.protocols.basic.LineReceiver.
8 This example uses generators to do the calculation. It also tries to be
9 a good example in division of responsibilities:
10 - The protocol handles the wire layer, reading in lists of numbers
11 and writing out the result.
12 - The factory decides on policy, and has relatively little knowledge
13 of the details of the protocol. Other protocols can use the same
14 factory class by intantiating and setting .protocol
15 - The factory does little job itself: it is mostly a policy maker.
16 The 'smarts' are in free-standing functions which are written
17 for flexibility.
18
19 The goal is for minimal dependencies:
20 - You can use runIterator to run any iterator inside the Twisted
21 main loop.
22 - You can use multiply whenever you need some way of multiplying
23 numbers such that the multiplications will happen asynchronously,
24 but it is your responsibility to schedule the multiplications.
25 - You can use the protocol with other factories to implement other
26 functions that apply to arbitrary lists of longs.
27 - You can use the factory with other protocols for support of legacy
28 protocols. In fact, the factory does not even have to be used as
29 a protocol factory. Here are easy ways to support the operation
30 over XML-RPC and PB.
31
32 class Multiply(xmlrpc.XMLRPC):
33 def __init__(self): self.factory = Multiplication()
34 def xmlrpc_multiply(self, *numbers):
35 return self.factory.calc(map(long, numbers))
36
37 class Multiply(pb.Referencable):
38 def __init__(self): self.factory = Multiplication()
39 def remote_multiply(self, *numbers):
40 return self.factory.calc(map(long, numbers))
41
42 Note:
43 Multiplying zero numbers is a perfectly sensible operation, and the
44 result is 1. In that, this example departs from doc/examples/longex.py,
45 which errors out when trying to do this.
46 """
47
48 from twisted.internet import defer, protocol
49 from twisted.protocols import basic
50
51
52 def runIterator(reactor, iterator):
53 try:
54 next(iterator)
55 except StopIteration:
56 pass
57 else:
58 reactor.callLater(0, runIterator, reactor, iterator)
59
60
61 def multiply(numbers):
62 d = defer.Deferred()
63
64 def _():
65 acc = 1
66 while numbers:
67 acc *= numbers.pop()
68 yield None
69 d.callback(acc)
70
71 return d, _()
72
73
74 class Numbers(basic.LineReceiver):
75 """Protocol for reading lists of numbers and manipulating them.
76
77 It receives a list of numbers (separated by whitespace) on a line, and
78 writes back the answer. The exact algorithm to use depends on the
79 factory. It should return an str-able Deferred.
80 """
81
82 def lineReceived(self, line):
83 try:
84 numbers = [int(num) for num in line.split()]
85 except ValueError:
86 self.sendLine(b"Error.")
87 return
88 deferred = self.factory.calc(numbers)
89
90 def encodeNumber(num):
91 return str(num).encode("ascii")
92
93 deferred.addCallback(encodeNumber)
94 deferred.addCallback(self.sendLine)
95
96
97 class Multiplication(protocol.ServerFactory):
98 """Factory for multiplying numbers.
99
100 It provides a function which calculates the multiplication
101 of a list of numbers. The function destroys its input.
102 Note that instances of this factory can use other formats
103 for transmitting the number lists, as long as they set
104 correct protoocl values.
105 """
106
107 protocol = Numbers
108
109 def calc(self, numbers):
110 deferred, iterator = multiply(numbers)
111 from twisted.internet import reactor
112
113 runIterator(reactor, iterator)
114 return deferred
115
116
117 if __name__ == "__main__":
118 from twisted.internet import reactor
119
120 reactor.listenTCP(1234, Multiplication())
121 reactor.run()