违法℃玩家 发表于 2017-4-25 10:53:43

Python&Thrift--Server&Client

  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 importPythonService
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 importPythonService
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]
查看完整版本: Python&Thrift--Server&Client