当前位置:首页 > 智能硬件 > 人工智能AI
[导读] Thrift_Python/…使用 Python/Node.js/Golang/Php… 都差不多,都可以完成服务和客户端的编写,这里以Python为例。

Thrift_Python/…使用

Python/Node.js/Golang/Php… 都差不多,都可以完成服务和客户端的编写,这里以Python为例。

Thrift的Python端既可以写服务器,也可以写客户端。 (Golang请参考之前的文章)

Server端

为了兼容JS端,我们这里都以一下要求为标准。

要求:(否则JS无法解析)

Json Protocol打包协议

Http Transport通信

MulTIpleProtocol/Processer(非必需)

1. 业务代码源

同其他语言,使用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()

之前写了太多服务端的代码,写的有点烦了,这里就不做太多解析,直接看代码就好。 ��

总结

Python作为脚本很简单好用,但是在编写严格的代码时真的很是抓狂,特备是Thrift这类文档不丰富的库时,简直要疯掉。

本篇的代码时通过Test项目学习得来的,路漫漫其修远兮~

这就是Thrift的坑,文档太少了。

其他语言的代码,这里省略了。如果有什么问题,请查看Test目录,参考学习。

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭