File: ampclient.py

package info (click to toggle)
twisted 25.5.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,560 kB
  • sloc: python: 203,171; makefile: 200; sh: 92; javascript: 36; xml: 31
file content (45 lines) | stat: -rw-r--r-- 1,144 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from ampserver import Divide, Sum

from twisted.internet import defer, reactor
from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol
from twisted.protocols.amp import AMP


def doMath():
    destination = TCP4ClientEndpoint(reactor, "127.0.0.1", 1234)
    sumDeferred = connectProtocol(destination, AMP())

    def connected(ampProto):
        return ampProto.callRemote(Sum, a=13, b=81)

    sumDeferred.addCallback(connected)

    def summed(result):
        return result["total"]

    sumDeferred.addCallback(summed)

    divideDeferred = connectProtocol(destination, AMP())

    def connected(ampProto):
        return ampProto.callRemote(Divide, numerator=1234, denominator=0)

    divideDeferred.addCallback(connected)

    def trapZero(result):
        result.trap(ZeroDivisionError)
        print("Divided by zero: returning INF")
        return 1e1000

    divideDeferred.addErrback(trapZero)

    def done(result):
        print("Done with math:", result)
        reactor.stop()

    defer.DeferredList([sumDeferred, divideDeferred]).addCallback(done)


if __name__ == "__main__":
    doMath()
    reactor.run()