Python Thrift 使用示例,附完整代码 - Go语言中文社区

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


系统环境:Mac

开发环境:Idea

Python版本:2.7

开发环境准备:idea可安装thrift插件,https://plugins.jetbrains.com/plugin/7331-thrift-support

Mac系统安装thrift:

brew install thrift

成功后:

$ thrift -version
Thrift version 0.12.0

06d47873472f97b6cf0e2cd8666f32cb1c8.jpg

编辑Thrift接口文件:ocrservice.thrift,内容如下:

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 为服务端代码

# 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脚本

thrift --gen py ocrservice.thrift

没有输出,看到当前目录下多一个目录,包含一系列文件,此时可以正常启动python进程了。

python server.py
python client.py

转载于:https://my.oschina.net/yaohonv/blog/3023223

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34344677/article/details/91924487
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 23:15:12
  • 阅读 ( 1404 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢