您的位置:首页 > 编程语言 > Python开发

thrift开发的例子(一)---python为例

2016-05-22 21:12 369 查看
1.编写thrift接口文件
2.thrift --gen 开发语言 thrift接口描述文件
如:thrift  --gen cpp student.thrift

thrift  --gen py student.thrift

3.利用生成的文件代码进行开发

1.简单的例子

struct employee{
    1:i16 id,
    2:string name
}
service HelloWorld{
    string ping(),
    string sayHello(1:string msg,2:employee e)
}

2.thrift-0.9.2.exe --gen py a.thrift (linux 下thrift --gen py a.thrift)
3.开发例子
客户端c.py

#coding=utf-8
import sys
sys.path.append('./gen-py')

from a.HelloWorld import Client
from a.ttypes import employee
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

transport = TSocket.TSocket('localhost', 9090)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Client(protocol)
transport.open()

print client.ping()
e = employee(1,'李小四')
print client.sayHello("!",e)

transport.close()

服务器端开发s.py

#!/usr/bin/env python
import socket
import sys
sys.path.append('./gen-py')
from a.HelloWorld import Processor
from a.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

class HelloHandler:
  def ping(self):
    return "ping"

  def sayHello(self, msg, e):
    print msg
    print e.id
    print e.name
    return 'hello '+e.name

handler = HelloHandler()
processor = Processor(handler)
transport = TSocket.TServerSocket("localhost", 9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print "Starting thrift server in python..."
server.serve()
print "done!"

附录:thrift数据类型规则
【基础类型】
(1)bool:布尔类型(true或false)
(2)byte:8位有符号整数
(3)i16:16位有符号整数
(4)i32:32位有符号整数
(5)i64:64位有符号整数
(6)double:64位浮点数
(7)string:文本字符串,使用UTF-8编码
【容器】
(1)list容器:一个元素可重复的有序列表。会被转换成C++中的vector,Java中的ArrayList,脚本语言中的数组等。
(2)set容器:一个元素不可重复的无序集合。会转换成C++中的set,Java中的HashSet、Python中的Set等。(熟悉PHP的同学可能会问“PHP并不支持set类型,怎么办”,在PHP语言中,
thrift会将set容器转换成List。)
(3)map容器:一个含有多个key:value键值对的结构。会被转换成C++中的map,Java中的HashMap,PHP中的关联数组,Python/Ruby中的dictionary等。
【结构体】
struct User{
        1:i32 id, 
        2:string name
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: