1、下載thrift,下載地址:http://archive.apache.org/dist/thrift/0.9.3/
2、在編寫python的thrift代碼時,需要先安裝thrift module,下載路徑:https://pypi.python.org/pypi/thrift/0.9.1
3、安裝thrift:在C盤新建一個Thtift文件夾,將下載的thrift-0.9.3.exe重新命名為thrift.exe后放到Thtift文件夾下,將該路徑添加到環境變量,檢驗是否安裝成功:在命令行中輸入:

即可以看到安裝后的版本信息。
4、thrift 采用IDL(Interface Definition Language)來定義通用的服務接口,並通過生成不同的語言代理實現來達到跨語言、平台的功能。在thrift的IDL中可以定義以下一些類型:基本數據類型,結構體,容器,異常、服務。
thrift腳本:
const string HELLO_YK = "yk"
service HelloWorld {
void ping(),
string sayHello(),
string sayMsg(1:string msg)
}
thrift腳本通過Thrift編輯器生成所要求的python開發語言代碼。即:

5、Thrift是一個典型的CS結構,客戶端和服務端可以使用不同的語言開發。本文以python為例:
PythonServer.py:
import sys
sys.path.append('./gen-py')
from helloworld import HelloWorld
from helloworld.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 HelloWorldHandler:
def __init__(self):
self.log = {}
def ping(self):
print "ping()"
def sayHello(self):
print "sayHello()"
return "say hello from " + socket.gethostbyname(socket.gethostname())
def sayMsg(self, msg):
print "sayMsg(" + msg + ")"
return "say " + msg + " from " + socket.gethostbyname(socket.gethostname())
handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket('127.0.0.1',30303)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "Starting python server..."
server.serve()
print "done!"
PythonClient.py
import sys
sys.path.append('./gen-py')
from helloworld import HelloWorld
from helloworld.ttypes import *
from helloworld.constants import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
# Make socket
transport = TSocket.TSocket('127.0.0.1', 30303)
# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)
# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)
# Create a client to use the protocol encoder
client = HelloWorld.Client(protocol)
# Connect!
transport.open()
client.ping()
print "ping()"
msg = client.sayHello()
print msg
msg = client.sayMsg(HELLO_YK)
print msg
transport.close()
except Thrift.TException, tx:
print "%s" % (tx.message)
運行結果:


文件下載:
