thrift目前只支持python2.6+,但不支持3.XX版本。
thrift下载:http://thrift.apache.org/
安装thrift:
./configure
make
make install
安装python的thrift组件
cd /usr/local/thrift-0.9.1/lib/py
python setup.py install
thrift模版文件PythonService.thrift
service PythonService{
string get(1:i32 id)
i32 remove(1:i32 id)
}
生成python文件
thrift --gen py PythonService.thrift
将gen-py/PythonService路径下的全部文件拷贝到自己的项目路径下,比如PythonThrift\servicePy
server端:
PythonThrift\server\PythonServiceServer.py
# coding=utf-8
'''
Created on 2013-9-22
@author: hanqunfeng
'''
import sys
sys.path.append('../') #导入上下文环境
from servicePy import PythonService
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TCompactProtocol
from thrift.server import TServer
import socket
# 实现类
class PythonServiceServer:
def get(self, id):
print socket.gethostbyname(socket.gethostname())
return "get=="+str(id)
def remove(self, id):
print socket.gethostbyname(socket.gethostname())
return id
handler = PythonServiceServer()
# 注册实现类
processor = PythonService.Processor(handler)
transport = TSocket.TServerSocket('localhost',30303)
tfactory = TTransport.TBufferedTransportFactory()
# pfactory = TBinaryProtocol.TBinaryProtocolFactory()
pfactory = TCompactProtocol.TCompactProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "Starting python server..."
server.serve()
print "done!"
client端:
PythonThrift\client\PythonServiceClient.py
# coding=utf-8
'''
Created on 2013-9-22
@author: hanqunfeng
'''
import sys
sys.path.append('../') #导入上下文环境
from servicePy import PythonService
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TCompactProtocol
def pythonServerExe():
try:
transport = TSocket.TSocket('localhost', 30303)
transport = TTransport.TBufferedTransport(transport)
# protocol = TBinaryProtocol.TBinaryProtocol(transport)
protocol = TCompactProtocol.TCompactProtocol(transport)
client = PythonService.Client(protocol)
transport.open()
print "The return value is : "
print client.remove(12)
print client.get(100)
print "............"
transport.close()
except Thrift.TException, tx:
print '%s' % (tx.message)
if __name__ == '__main__':
pythonServerExe()
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com