基于Test來(lái)使用12-Thrift_Python
Thrift_Python/…使用
Python/Node.js/Golang/Php… 都差不多,都可以完成服務(wù)和客戶端的編寫(xiě),這里以Python為例。
Thrift的Python端既可以寫(xiě)服務(wù)器,也可以寫(xiě)客戶端。 (Golang請(qǐng)參考之前的文章)
Server端
為了兼容JS端,我們這里都以一下要求為標(biāo)準(zhǔn)。
要求:(否則JS無(wú)法解析)
Json Protocol打包協(xié)議
Http Transport通信
MulTIpleProtocol/Processer(非必需)
1. 業(yè)務(wù)代碼源
同其他語(yǔ)言,使用thrift編譯工具,將xxx.thrift文件編譯為xx.py文件,通過(guò)pip安裝thrift基礎(chǔ)python庫(kù)即可。
參考命令: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()
這個(gè)代碼可以仿照Golang的Demo,幾乎一樣。
吐槽一下:Python的包機(jī)制真是個(gè)坑!?。?/p>
Client端
不多說(shuō)什么,直接看代碼吧~~
Robot源代碼庫(kù)使用服務(wù)器那份,方法相同。
# 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()
之前寫(xiě)了太多服務(wù)端的代碼,寫(xiě)的有點(diǎn)煩了,這里就不做太多解析,直接看代碼就好。 ??
總結(jié)
Python作為腳本很簡(jiǎn)單好用,但是在編寫(xiě)嚴(yán)格的代碼時(shí)真的很是抓狂,特備是Thrift這類文檔不豐富的庫(kù)時(shí),簡(jiǎn)直要瘋掉。
本篇的代碼時(shí)通過(guò)Test項(xiàng)目學(xué)習(xí)得來(lái)的,路漫漫其修遠(yuǎn)兮~
這就是Thrift的坑,文檔太少了。
其他語(yǔ)言的代碼,這里省略了。如果有什么問(wèn)題,請(qǐng)查看Test目錄,參考學(xué)習(xí)。