Thrift_Python/…使用
Python/Node.js/Golang/Php… 都差不多,都可以完成服務和客戶端的編寫,這里以Python為例。
Thrift的Python端既可以寫服務器,也可以寫客戶端。 (Golang請參考之前的文章)
Server端
為了兼容JS端,我們這里都以一下要求為標準。
要求:(否則JS無法解析)
Json Protocol打包協(xié)議
Http Transport通信
MulTIpleProtocol/Processer(非必需)
1. 業(yè)務代碼源
同其他語言,使用thrift編譯工具,將xxx.thrift文件編譯為xx.py文件,通過pip安裝thrift基礎python庫即可。
參考命令:thrift -o . -out ./pyModule --gen py Robot.thrift , pip install thrift
2. 使用方法# coding: utf-8importsys sys.path.append("./pyModule")fromthrift.transporTImportTHttpServerfromthrift.protocolimportTJSONProtocolfromthrift.protocol.TMulTIplexedProtocolimportTMulTIplexedProtocolimportRobotimportRobot.AudioclassRobotAudioHandle:defTtsPlay(self, strTxt, nPlayPriority):""" Parameters: - strTxt - nPlayPriority """print("RobotAudioHandle:",strTxt,nPlayPriority)passhandler = RobotAudioHandle() processor = Robot.Audio.Processor(handler) server = THttpServer.THttpServer(TMultiplexedProcessor(processor,"Audio"), ("127.0.0.1",9000), TJSONProtocol.TJSONProtocolFactory) print("Server start...") server.serve()
這個代碼可以仿照Golang的Demo,幾乎一樣。
吐槽一下:Python的包機制真是個坑?。?!
Client端
不多說什么,直接看代碼吧~~
Robot源代碼庫使用服務器那份,方法相同。
# coding: utf-8importsys sys.path.append("./pyModule")fromthrift.transport.THttpClientimportTHttpClientfromthrift.protocol.TJSONProtocolimportTJSONProtocolfromthrift.protocol.TMultiplexedProtocolimportTMultiplexedProtocolimportRobotimportRobot.AudioclassRobotProxy:defflush(self):sys.stdout.flush()def__init__(self):self.Robot_tans =Noneself.protocol =Noneself.Audio =Noneself.Robot_tans = THttpClient("http://127.0.0.1:9000/robot") self.protocol = TJSONProtocol(self.Robot_tans)try: self.Audio = Robot.Audio.Client(TMultiplexedProtocol(self.protocol,"Audio"))except: print("Audio Proxy error!")try: self.Robot_tans.open()except: print("Robot_tans or protocol error!") print("Load RobotProxy Module...") app = RobotProxy()
之前寫了太多服務端的代碼,寫的有點煩了,這里就不做太多解析,直接看代碼就好。 ??
總結(jié)
Python作為腳本很簡單好用,但是在編寫嚴格的代碼時真的很是抓狂,特備是Thrift這類文檔不豐富的庫時,簡直要瘋掉。
本篇的代碼時通過Test項目學習得來的,路漫漫其修遠兮~
這就是Thrift的坑,文檔太少了。
其他語言的代碼,這里省略了。如果有什么問題,請查看Test目錄,參考學習。