Python Thrift 使用示例,附完整代碼

系統環境:Macjava

開發環境:Ideapython

Python版本:2.7bash

開發環境準備:idea可安裝thrift插件,https://plugins.jetbrains.com/plugin/7331-thrift-supportapp

Mac系統安裝thrift:ide

brew install thrift

成功後:ui

$ thrift -version
Thrift version 0.12.0

編輯Thrift接口文件:ocrservice.thrift,內容以下:idea

namespace cpp test
namespace java com.test.thrift

service OCRService {
   string recognizeWithFile(1:binary file, 2:string uuid, 3:map<string, string> meta);
}

server.py 爲服務端代碼spa

# coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# Add import thrift.
sys.path.append('gen-py')
from ocrservice import OCRService
from ocrservice.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import logging
logging.basicConfig(level=logging.INFO)

# Import prds
sys.path.append('prds')

class OCRHandler:

    def __init__(self):
        print("handler")

    def recognizeWithFile(self, image_buffer, uuid, meta):
        print("get from client")
        return "hello there!"

if __name__ == '__main__':
    print("begin...")
    handler = OCRHandler()
    processor = OCRService.Processor(handler)
    transport = TSocket.TServerSocket("127.0.0.1", "9080")
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

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

    print "Starting thrift service......"
    server.serve()
    print "Done!"

client.py 爲客戶端代碼插件

#!/usr/bin/python
# coding:utf-8

import sys, os, re
sys.path.append('gen-py')

# Add import thrift
from ocrservice import OCRService
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:
    transport = TSocket.TSocket("127.0.0.1", 9080)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = OCRService.Client(protocol)
    transport.open()
    print client.recognizeWithFile(None, None, None)

    transport.close()

except Thrift.TException, ex:
    print "%s" % (ex.message)

 

啓動server端前,須要用thrift命令生產python腳本code

thrift --gen py ocrservice.thrift

沒有輸出,看到當前目錄下多一個目錄,包含一系列文件,此時能夠正常啓動python進程了。

python server.py
python client.py
相關文章
相關標籤/搜索