blob: 6130b92d4bca6723bcc04017ffdc884f2e56f435 [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
22import sys
23sys.path.append('../gen-py.twisted')
24
25from tutorial import Calculator
26from tutorial.ttypes import *
27
28from shared.ttypes import SharedStruct
29
30from zope.interface import implements
31from twisted.internet import reactor
32
33from thrift.transport import TTwisted
34from thrift.protocol import TBinaryProtocol
35from thrift.server import TServer
36
37class CalculatorHandler:
38 implements(Calculator.Iface)
39 def __init__(self):
40 self.log = {}
41
42 def ping(self):
43 print 'ping()'
44
45 def add(self, n1, n2):
46 print 'add(%d,%d)' % (n1, n2)
47 return n1+n2
48
49 def calculate(self, logid, work):
50 print 'calculate(%d, %r)' % (logid, work)
51
52 if work.op == Operation.ADD:
53 val = work.num1 + work.num2
54 elif work.op == Operation.SUBTRACT:
55 val = work.num1 - work.num2
56 elif work.op == Operation.MULTIPLY:
57 val = work.num1 * work.num2
58 elif work.op == Operation.DIVIDE:
59 if work.num2 == 0:
60 x = InvalidOperation()
61 x.what = work.op
62 x.why = 'Cannot divide by 0'
63 raise x
64 val = work.num1 / work.num2
65 else:
66 x = InvalidOperation()
67 x.what = work.op
68 x.why = 'Invalid operation'
69 raise x
70
71 log = SharedStruct()
72 log.key = logid
73 log.value = '%d' % (val)
74 self.log[logid] = log
75
76 return val
77
78 def getStruct(self, key):
79 print 'getStruct(%d)' % (key)
80 return self.log[key]
81
82 def zip(self):
83 print 'zip()'
84
85if __name__ == '__main__':
86 handler = CalculatorHandler()
87 processor = Calculator.Processor(handler)
88 pfactory = TBinaryProtocol.TBinaryProtocolFactory()
89 server = reactor.listenTCP(9090,
90 TTwisted.ThriftServerFactory(processor,
91 pfactory), interface="127.0.0.1")
92 reactor.run()