| 1 |
from twisted.protocols import amp |
| 2 |
|
| 3 |
|
| 4 |
class Sum(amp.Command): |
| 5 |
arguments = [(b"a", amp.Integer()), (b"b", amp.Integer())] |
| 6 |
response = [(b"total", amp.Integer())] |
| 7 |
|
| 8 |
|
| 9 |
class Divide(amp.Command): |
| 10 |
arguments = [(b"numerator", amp.Integer()), (b"denominator", amp.Integer())] |
| 11 |
response = [(b"result", amp.Float())] |
| 12 |
errors = {ZeroDivisionError: b"ZERO_DIVISION"} |
| 13 |
|
| 14 |
|
| 15 |
class Math(amp.AMP): |
| 16 |
def sum(self, a, b): |
| 17 |
total = a + b |
| 18 |
print(f"Did a sum: {a} + {b} = {total}") |
| 19 |
return {"total": total} |
| 20 |
|
| 21 |
Sum.responder(sum) |
| 22 |
|
| 23 |
def divide(self, numerator, denominator): |
| 24 |
result = float(numerator) / denominator |
| 25 |
print(f"Divided: {numerator} / {denominator} = {result}") |
| 26 |
return {"result": result} |
| 27 |
|
| 28 |
Divide.responder(divide) |
| 29 |
|
| 30 |
|
| 31 |
def main(): |
| 32 |
from twisted.internet import reactor |
| 33 |
from twisted.internet.protocol import Factory |
| 34 |
|
| 35 |
pf = Factory() |
| 36 |
pf.protocol = Math |
| 37 |
reactor.listenTCP(1234, pf) |
| 38 |
print("started") |
| 39 |
reactor.run() |
| 40 |
|
| 41 |
|
| 42 |
if __name__ == "__main__": |
| 43 |
main() |