一 安装环境
1 python安装thrift包
pip install thrift
2 下载win版本的“thrift-0.11.0.exe”
http://thrift.apache.org/download
3 安装pychar的thrift插件,用于提高编写thrift的自动补全
https://plugins.jetbrains.com/plugin/7331-thrift-support
把下载的“intellij-thrift.zip”解压出来之后的.jar文件拷贝到pycharm安装目录下的lib目录下。
二 实现一个hello的例子
1 定义hello.thrift
2 用thrift编译器编译(使用了Cygwin64 Terminal)
$ ./thrift-0.11.0.exe -r -gen py hello.thrift
这样就生成了py的代码了,在"gen-py"。这个包可以被后面自己写的服务端和客户端代码使用。
3 建立python的工程
用pycharm建立工程"thrift_hello"工程,然后把上一步生成的软件包拷贝到这个工程目录下。工程目录如下。因为python中,包的路径好像不支持'-',因此要把“gen-py”重命名成'gen_py'。
4 编写客户端和服务端的实现代码。
hello_server.py
from gen_py.hello import Hello
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TSocket, TTransport
__HOST = '127.0.0.1'
__PORT = 9090
class hello_handle:
def helloString(self, para):
print(para)
return "result:" + para
if __name__ == '__main__':
# 创建服务端
handler = hello_handle()
processor = Hello.Processor(handler)
# 监听端口
transport = TSocket.TServerSocket(host=__HOST, port=__PORT)
# 选择传输层
tfactory = TTransport.TBufferedTransportFactory()
# 选择传输协议
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
# 创建服务端
server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
server.setNumThreads(5)
print('Starting the server')
server.serve()
print('done')
hello_client.py
from gen_py.hello import Hello
from thrift.Thrift import TException
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TProtocol
from thrift.transport import TSocket, TTransport
__HOST = '127.0.0.1'
__PORT = 9090
if __name__ == '__main__':
try:
print('客户端启动....')
transport = TSocket.TSocket(host=__HOST, port=__PORT)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Hello.Client(protocol)
transport.open()
result = client.helloString("hello")
print(result)
transport.close()
print('done')
except TException as e:
print(e)
5 运行代码
1 先运行hello_server
2 运行hello_client输出结果: