Thrift的服务器和客户端Python案例
生活随笔
收集整理的這篇文章主要介紹了
Thrift的服务器和客户端Python案例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
服務(wù)器
Thrift提供的常見服務(wù)端類型有一下幾種:
- thrift.server.TServer.TSimpleServer?單線程服務(wù)器
- thrift.server.TServer.TThreadedServer?多線程服務(wù)器
- thrift.server.TServer.TThreadPoolServer?線程池服務(wù)器
- thrift.server.TServer.TForkingServer?多進程服務(wù)器
我們以線程池服務(wù)器為例,其他方式相同。
import sys
sys.path.append('gen-py') # 增加生成代碼的查找包路徑from calculate import Calculate
from base.ttypes import InvalidOperation, Operationfrom thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol
from thrift.server import TServerclass CalculateHandler(Calculate.Iface):"""被調(diào)用方法的具體實現(xiàn)"""def ping(self):print('ping()')def divide(self, num1, num2):if num2 == 0:raise InvalidOperation(0, 'Cannot divide by 0')return num1 / num2def calculate(self, work):if work.op == Operation.ADD:val = work.num1 + work.num2elif work.op == Operation.SUBTRACT:val = work.num1 - work.num2elif work.op == Operation.MULTIPLY:val = work.num1 * work.num2else: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('服務(wù)器已啟動')
客戶端
import sys
sys.path.append('gen-py')from calculate import Calculate
from base.ttypes import InvalidOperation, Operation, Workfrom thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocoldef main():transport = TSocket.TSocket('127.0.0.1', 8888)# 使用緩存?zhèn)鬏攖ransport = TTransport.TBufferedTransport(transport)# 使用壓縮的二進制消息協(xié)議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))# 關(guān)閉transport.close()if __name__ == '__main__':main()
?
總結(jié)
以上是生活随笔為你收集整理的Thrift的服务器和客户端Python案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Thrift协议与传输选择
- 下一篇: Windows系统下安装Thrift的方