blob: 227f6d4a215d6ba28842c2f8b0a22f9314d48c8a [file] [log] [blame]
Roger Meiercd9bc462011-01-03 20:19:07 +00001#!/usr/bin/env python
2
3#
4# Licensed to the Apache Software Foundation (ASF) under one
5# or more contributor license agreements. See the NOTICE file
6# distributed with this work for additional information
7# regarding copyright ownership. The ASF licenses this file
8# to you under the Apache License, Version 2.0 (the
9# "License"); you may not use this file except in compliance
10# with the License. You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing,
15# software distributed under the License is distributed on an
16# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17# KIND, either express or implied. See the License for the
18# specific language governing permissions and limitations
19# under the License.
20#
21
Roger Meier1d66d062012-10-26 21:46:18 +000022import sys, glob
23sys.path.append('gen-py.twisted')
24sys.path.insert(0, glob.glob('../../lib/py/build/lib.*')[0])
Roger Meiercd9bc462011-01-03 20:19:07 +000025
26from tutorial import Calculator
27from tutorial.ttypes import *
28
29from shared.ttypes import SharedStruct
30
31from zope.interface import implements
32from twisted.internet import reactor
33
34from thrift.transport import TTwisted
35from thrift.protocol import TBinaryProtocol
36from thrift.server import TServer
37
38class CalculatorHandler:
39 implements(Calculator.Iface)
40 def __init__(self):
41 self.log = {}
42
43 def ping(self):
44 print 'ping()'
45
46 def add(self, n1, n2):
47 print 'add(%d,%d)' % (n1, n2)
48 return n1+n2
49
50 def calculate(self, logid, work):
51 print 'calculate(%d, %r)' % (logid, work)
52
53 if work.op == Operation.ADD:
54 val = work.num1 + work.num2
55 elif work.op == Operation.SUBTRACT:
56 val = work.num1 - work.num2
57 elif work.op == Operation.MULTIPLY:
58 val = work.num1 * work.num2
59 elif work.op == Operation.DIVIDE:
60 if work.num2 == 0:
61 x = InvalidOperation()
Konrad Grochowski3b115df2015-05-18 17:58:36 +020062 x.whatOp = work.op
Roger Meiercd9bc462011-01-03 20:19:07 +000063 x.why = 'Cannot divide by 0'
64 raise x
65 val = work.num1 / work.num2
66 else:
67 x = InvalidOperation()
Konrad Grochowski3b115df2015-05-18 17:58:36 +020068 x.whatOp = work.op
Roger Meiercd9bc462011-01-03 20:19:07 +000069 x.why = 'Invalid operation'
70 raise x
71
72 log = SharedStruct()
73 log.key = logid
74 log.value = '%d' % (val)
75 self.log[logid] = log
76
77 return val
78
79 def getStruct(self, key):
80 print 'getStruct(%d)' % (key)
81 return self.log[key]
82
83 def zip(self):
84 print 'zip()'
85
86if __name__ == '__main__':
87 handler = CalculatorHandler()
88 processor = Calculator.Processor(handler)
89 pfactory = TBinaryProtocol.TBinaryProtocolFactory()
90 server = reactor.listenTCP(9090,
91 TTwisted.ThriftServerFactory(processor,
92 pfactory), interface="127.0.0.1")
93 reactor.run()