thrift的python实现,简单实例

thrift的python实现,简单实例

参考自:乱糟糟

首先需要定义一个.thrift文件,通过thrift语法编写目标代码逻辑,通过thrift生成相应语言(如python/java)的代码逻辑。

客户端和服务端的实现都基于生成的thrift代码;服务端把代码实现,客户端使用API的存根,直接调用。

windows安装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.pyclient.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.pyclient.py(如果路径报错,修改即可),程序可正常运行。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值