thrift的python实现,简单实例
参考自:乱糟糟
首先需要定义一个.thrift
文件,通过thrift语法编写目标代码逻辑,通过thrift生成相应语言(如python/java)的代码逻辑。
客户端和服务端的实现都基于生成的thrift代码;服务端把代码实现,客户端使用API的存根,直接调用。
windows安装thrift
- thrift下载地址
- python:3.x
- pip install thrift
1. 编写thrift文件
test.thrift
service Transmit {
string sayMsg(1:string msg);
string invoke(1:i32 cmd 2:string token 3:string data)
}
2. 生成thrift代码
执行命令,在当前目录下生成了一套thrfit代码,我这里使用的是thrift-0.9.3.exe版本的thrift。
thrift-0.9.3.exe -gen py test.thrift
接下来构建server.py
和client.py
文件,implement server/client
业务逻辑。
server.py
import json
from test import Transmit
from test.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import socket
class TransmitHandler:
def __init__(self):
self.log = {}
def sayMsg(self, msg):
msg = json.loads(msg)
print("sayMsg(" + msg + ")")
return "say " + msg + " from " + socket.gethostbyname(socket.gethostname())
def invoke(self,cmd,token,data):
cmd = cmd
token =token
data = data
if cmd ==1:
return json.dumps({token:data})
else:
return 'cmd不匹配'
if __name__=="__main__":
handler = TransmitHandler()
processor = Transmit.Processor(handler)
transport = TSocket.TServerSocket('127.0.0.1', 8000)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print("Starting python server...")
server.serve()
client.py
import sys
import jsonfrom test import Transmit
from test.ttypes import *
from test.constants import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
transport = TSocket.TSocket('127.0.0.1', 8000)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Transmit.Client(protocol)
# Connect!
transport.open()
cmd = 2
token = '1111-2222-3333-4444'
data = json.dumps({"name":"zhoujielun"})
msg = client.invoke(cmd,token,data)
print(msg)
transport.close()
# 执行结果:cmd不匹配
分别运行server.py
和client.py
(如果路径报错,修改即可),程序可正常运行。