前面已经实现了纯java的thrift的实现。
现在实现实现一下python作为客户端和服务端的thrift的调用
1.python作为客户端,java作为服务端
java服务端代码参考前面写的博客
客户端python的准备:
1.使用mac下的PyCharm,专业的python开发工具
2.生成python代码
thrift --gen py thrift/data.thrift
3.在mac下安装thrift的python依赖
sudo python setup.py install 安装thrift的python依赖
4.查看安装依赖的路径
安装的路径:/Library/Python/2.7/site-packages
python客户端代码 :
#-*- coding:utf-8 -*-
__author__ = ‘作者‘
//导入thrift生成的业务代码
from py.com.fubin.netty importPersonServicefrom py.com.fubin.netty importttypes
//导入thrift框架的代码from thrift importThriftfrom thrift.transport importTSocketfrom thrift.transport importTTransportfrom thrift.protocol importTCompactProtocol
//解决中文乱码问题importsys
reload(sys)
sys.setdefaultencoding(‘utf-8‘)try:
tSocket= TSocket.TSocket("localhost",8899)
tSocket.setTimeout(600)
transport=TTransport.TFramedTransport(tSocket)
protocol=TCompactProtocol.TCompactProtocol(transport)
client=PersonService.Client(protocol)
transport.open()
person= client.getPersonByUsername("zhangsan")printperson.usernameprintperson.ageprintperson.marriedprint ‘=======================‘newPerson=ttypes.Person()
newPerson.username= "付彬"newPerson.age= 11newPerson.married=True
client.savePerson(newPerson)
transport.close()exceptThrift.TException , tx:print ‘%s‘ % tx.message
中文乱码问题:导入系统库
importsys
reload(sys)
sys.setdefaultencoding(‘utf-8‘)
python作为服务端
1.编写业务接口类
#-*- coding:utf-8 -*-
__author__ = ‘作者‘
from py.com.fubin.netty importttypesclassPersonServiceImpl :defgetPersonByUsername(self,username):print "got client param :" +username
person=ttypes.Person()
person.username=username
person.age= 112person.married=TruereturnpersondefsavePerson(self ,person):print "got client param :"
printperson.usernameprintperson.ageprint person.married
编写服务端初始化类:
#-*- coding:utf-8 -*-
__author__ = ‘作者‘
from py.com.fubin.netty importPersonServicefrom PythonServiceImpl importPersonServiceImplfrom py.com.fubin.netty importttypesfrom thrift importThriftfrom thrift.transport importTSocketfrom thrift.transport importTTransportfrom thrift.protocol importTCompactProtocolfrom thrift.server importTServerimportsys
reload(sys)
sys.setdefaultencoding(‘utf-8‘)try:
personServiceHandler=PersonServiceImpl()
processor=PersonService.Processor(personServiceHandler)
serverSocket= TSocket.TServerSocket(port=8899)
transportFactory=TTransport.TFramedTransportFactory()
protocolFactory=TCompactProtocol.TCompactProtocolFactory()
server=TServer.TSimpleServer(processor,serverSocket,transportFactory,protocolFactory)
server.serve()exceptThrift.TException , tx:print ‘%s‘ % tx.message
到这里,一个简单的python实现的thrift调用例子就完成了。
不积跬步,无以至千里,每天进步一点点。
原文地址:http://www.cnblogs.com/fubinhnust/p/7302462.html