Debian Codegraph @

docs/core/examples/longex.py

raw
1 """Simple example of doing arbitrarily long calculations nicely in Twisted.
2
3 This is also a simple demonstration of twisted.protocols.basic.LineReceiver.
4 """
5
6 from twisted.internet import reactor
7 from twisted.internet.protocol import ServerFactory
8 from twisted.protocols import basic
9
10
11 class LongMultiplicationProtocol(basic.LineReceiver):
12 """A protocol for doing long multiplications.
13
14 It receives a list of numbers (separated by whitespace) on a line, and
15 writes back the answer. The answer is calculated in chunks, so no one
16 calculation should block for long enough to matter.
17 """
18
19 def connectionMade(self):
20 self.workQueue = []
21
22 def lineReceived(self, line):
23 try:
24 numbers = [int(num) for num in line.split()]
25 except ValueError:
26 self.sendLine(b"Error.")
27 return
28
29 if len(numbers) <= 1:
30 self.sendLine(b"Error.")
31 return
32
33 self.workQueue.append(numbers)
34 reactor.callLater(0, self.calcChunk)
35
36 def calcChunk(self):
37 # Make sure there's some work left; when multiple lines are received
38 # while processing is going on, multiple calls to reactor.callLater()
39 # can happen between calls to calcChunk().
40 if self.workQueue:
41 # Get the first bit of work off the queue
42 work = self.workQueue[0]
43
44 # Do a chunk of work: [a, b, c, ...] -> [a*b, c, ...]
45 work[:2] = [work[0] * work[1]]
46
47 # If this piece of work now has only one element, send it.
48 if len(work) == 1:
49 self.sendLine(str(work[0]).encode("ascii"))
50 del self.workQueue[0]
51
52 # Schedule this function to do more work, if there's still work
53 # to be done.
54 if self.workQueue:
55 reactor.callLater(0, self.calcChunk)
56
57
58 class LongMultiplicationFactory(ServerFactory):
59 protocol = LongMultiplicationProtocol
60
61
62 if __name__ == "__main__":
63 import sys
64
65 from twisted.python import log
66
67 log.startLogging(sys.stdout)
68 reactor.listenTCP(1234, LongMultiplicationFactory())
69 reactor.run()