thrift实例:python实现

 

编译版本: python 2.7+, thrift-0.10.0.exe

参考文档: 

http://www.tuicool.com/articles/FnY3eiQ

http://www.cnblogs.com/enternal/p/5275455.html

https://my.oschina.net/u/780876/blog/691293

https://my.oschina.net/michao/blog/550416

 

项目目录结构

<项目名>:

    test: 测试代码包

    ds: 数据结构包,thrift生成的py放在这里

    thrift: thrift文件存储目录

 

代码

helloworld.thrift

#helloworld.thrift
#建议设定namespace
namespace java org.sl.thrift
namespace py slthrift

service Hello  {
    string helloString(1:string word)
}

 

生成python代码 (windows下,需要下载thrift编译器, http://apache.fayea.com/thrift/0.10.0/thrift-0.10.0.exe,建议改个名)

thrift --gen py -out ../ds helloworld.thrift

执行后,会在ds目录下生成 (子目录slthrift)python代码

 

test目录下,python 测试代码

thriftserver.py

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'shanl'
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('../ds/slthrift') #注意这里

from slthrift import Hello
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

SERVICE_CFG = {
    'ip': '0.0.0.0',  #向所有ip开放
    'port': 9000
}

class HelloHandler(Hello.Iface):
    def helloString(self, word):
        ret = "Received: " + word
        return ret

handler = HelloHandler()
processor = Hello.Processor(handler)
transport = TSocket.TServerSocket(SERVICE_CFG['ip'], SERVICE_CFG['port'])
tfactory = TTransport.TBufferedTransportFactory()
pfactory  = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "thrift server listen in '%s:%s'." % (SERVICE_CFG['ip'], SERVICE_CFG['port'])
server.serve()
print "done!"

 

thriftclient.py

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'shanl'
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('../ds/slthrift')

from slthrift import Hello
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
import random

SERVICE_CFG = {
    'ip': '127.0.0.1',
    'port': 9000
}

transport = TSocket.TSocket(SERVICE_CFG['ip'], SERVICE_CFG['port'])
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Hello.Client(protocol)
transport.open()
for i in xrange(100):
    print client.helloString('%s' % (random.randint(1000, 9999)))
transport.close()

 

转载于:https://my.oschina.net/tangcoffee/blog/882540

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值