twn39 / code

:memo: 代码笔记,通过 issue 的方式记录日常遇到的问题和学习笔记
13 stars 1 forks source link

Thrift python #96

Open twn39 opened 8 years ago

twn39 commented 8 years ago

注: thrift 不支持 python 3

thrift -r --gen py app.thrift

使用conda分配python 2.7环境,用pip安装thrift包:pip install thrift

app.thrift:

service Light {
    string hello(1:string name)
}
twn39 commented 8 years ago

server.py:

import sys 
sys.path.append('gen-py')

from app import Light
from app.ttypes import *

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

class Handler:

    def __init__(self):
        self.log = {}

    def hello(self, name):

        return name

if __name__ == '__main__':
    handler = Handler()
    processor = Light.Processor(handler)
    transport = TSocket.TServerSocket(port = 9090)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    print "Starting thrift server in python..."
    server.serve()
twn39 commented 8 years ago

Client.py:

import sys
sys.path.append('gen-py')

from app import Light
from app.ttypes import *

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

transport = TSocket.TSocket()
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)

client = Light.Client(protocol)

transport.open()
print(client.hello('kevin'))

transport.close()