Flask接口签名sign原理与实例代码浅析
333
2022-09-05
Thrift的服务器和客户端Python案例(thrift Python)
服务器
Thrift提供的常见服务端类型有一下几种:
thrift.server.TServer.TSimpleServer单线程服务器thrift.server.TServer.TThreadedServer多线程服务器thrift.server.TServer.TThreadPoolServer线程池服务器thrift.server.TServer.TForkingServer多进程服务器
我们以线程池服务器为例,其他方式相同。
import syssys.path.append('gen-py') # 增加生成代码的查找包路径from calculate import Calculatefrom base.ttypes import InvalidOperation, Operationfrom thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TCompactProtocolfrom thrift.server import TServerclass CalculateHandler(Calculate.Iface): """被调用方法的具体实现""" def ping(self): print('ping()') def divide(self, num1, num2): if num2 == 0: raise InvalidOperation(0, 'Cannot divide by 0') return num1 / num2 def calculate(self, work): if work.op == Operation.ADD: val = work.num1 + work.num2 elif work.op == Operation.SUBTRACT: val = work.num1 - work.num2 elif work.op == Operation.MULTIPLY: val = work.num1 * work.num2 else: raise InvalidOperation(work.op, 'Invalid operation') return valif __name__ == '__main__': handler = CalculateHandler() processor = Calculate.Processor(handler) transport = TSocket.TServerSocket(host='127.0.0.1', port=8888) tfactory = TTransport.TBufferedTransportFactory() pfactory = TCompactProtocol.TCompactProtocolFactory() server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) server.serve() print('服务器已启动')
客户端
import syssys.path.append('gen-py')from calculate import Calculatefrom base.ttypes import InvalidOperation, Operation, Workfrom thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TCompactProtocoldef main(): transport = TSocket.TSocket('127.0.0.1', 8888) # 使用缓存传输 transport = TTransport.TBufferedTransport(transport) # 使用压缩的二进制消息协议 protocol = TCompactProtocol.TCompactProtocol(transport) client = Calculate.Client(protocol) # 连接 transport.open() client.ping() print('ping()') result = client.divide(100, 50) print('100/50={}'.format(result)) try: result = client.divide(100, 0) except InvalidOperation as e: print(e.why) work = Work(1, 2, Operation.ADD) result = client.calculate(work) print('1+2={}'.format(result)) work = Work(15, 10, Operation.SUBTRACT) result = client.calculate(work) print('15-10={}'.format(result)) # 关闭 transport.close()if __name__ == '__main__': main()
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~