Debian Codegraph @

docs/core/examples/streaming.py

raw
1 #!/usr/bin/env python
2
3 # Copyright (c) Twisted Matrix Laboratories.
4 # See LICENSE for details.
5
6 """
7 This is a sample implementation of a Twisted push producer/consumer system. It
8 consists of a TCP server which asks the user how many random integers they
9 want, and it sends the result set back to the user, one result per line,
10 and finally closes the connection.
11 """
12
13
14 from random import randrange
15 from sys import stdout
16
17 from zope.interface import implementer
18
19 from twisted.internet import interfaces, reactor
20 from twisted.internet.protocol import Factory
21 from twisted.protocols.basic import LineReceiver
22 from twisted.python.log import startLogging
23
24
25 @implementer(interfaces.IPushProducer)
26 class Producer:
27 """
28 Send back the requested number of random integers to the client.
29 """
30
31 def __init__(self, proto, count):
32 self._proto = proto
33 self._goal = count
34 self._produced = 0
35 self._paused = False
36
37 def pauseProducing(self):
38 """
39 When we've produced data too fast, pauseProducing() will be called
40 (reentrantly from within resumeProducing's sendLine() method, most
41 likely), so set a flag that causes production to pause temporarily.
42 """
43 self._paused = True
44 print(f"Pausing connection from {self._proto.transport.getPeer()}")
45
46 def resumeProducing(self):
47 """
48 Resume producing integers.
49
50 This tells the push producer to (re-)add itself to the main loop and
51 produce integers for its consumer until the requested number of integers
52 were returned to the client.
53 """
54 self._paused = False
55
56 while not self._paused and self._produced < self._goal:
57 next_int = randrange(0, 10000)
58 line = f"{next_int}"
59 self._proto.sendLine(line.encode("ascii"))
60 self._produced += 1
61
62 if self._produced == self._goal:
63 self._proto.transport.unregisterProducer()
64 self._proto.transport.loseConnection()
65
66 def stopProducing(self):
67 """
68 When a consumer has died, stop producing data for good.
69 """
70 self._produced = self._goal
71
72
73 class ServeRandom(LineReceiver):
74 """
75 Serve up random integers.
76 """
77
78 def connectionMade(self):
79 """
80 Once the connection is made we ask the client how many random integers
81 the producer should return.
82 """
83 print(f"Connection made from {self.transport.getPeer()}")
84 self.sendLine(b"How many random integers do you want?")
85
86 def lineReceived(self, line):
87 """
88 This checks how many random integers the client expects in return and
89 tells the producer to start generating the data.
90 """
91 count = int(line.strip())
92 print(f"Client requested {count} random integers!")
93 producer = Producer(self, count)
94 self.transport.registerProducer(producer, True)
95 producer.resumeProducing()
96
97 def connectionLost(self, reason):
98 print(f"Connection lost from {self.transport.getPeer()}")
99
100
101 startLogging(stdout)
102 factory = Factory()
103 factory.protocol = ServeRandom
104 reactor.listenTCP(1234, factory)
105 reactor.run()