编译版本: 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#建议设定namespacenamespace java org.sl.thriftnamespace py slthriftservice 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 sysreload(sys)sys.setdefaultencoding('utf-8')sys.path.append('../ds/slthrift') #注意这里from slthrift import Hellofrom thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocolfrom thrift.server import TServerSERVICE_CFG = { 'ip': '0.0.0.0', #向所有ip开放 'port': 9000}class HelloHandler(Hello.Iface): def helloString(self, word): ret = "Received: " + word return rethandler = 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 sysreload(sys)sys.setdefaultencoding('utf-8')sys.path.append('../ds/slthrift')from slthrift import Hellofrom thrift.transport import TSocketfrom thrift.protocol import TBinaryProtocolimport randomSERVICE_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()