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
相关文章
相关标签/搜索