python使用grpc,并打包成python模块

  • xmlrpc也是可行的方案,也相对更加简单

一、环境
python3.6
二、安装模块

pip3 install grpcio
pip3 install protobuf
pip3 install grpcio-tools

三、准备grpc配置文件grpcdatabase.proto
目录结构:

内容如下:

syntax = "proto3";
package grpcServer;
service Greeter {
    rpc GetContent (Request) returns (Return) {} //定义要调用的函数(GetContent)+(Request)接受的参数+(Return)返回的参数
}

message Request {       //传参数据类型
    string content = 1;//文本
    int32 code=2;      //返回状态0success;1failed
}

message Return {       //返回数据类型
    string message = 1;//文本
    int32 code=2;      //返回状态0success;1failed
}
//执行命令+安装步骤
//python3 -m grpc_tools.protoc -I. --python_out=grpc_base_models/ --grpc_python_out=grpc_base_models/ grpcdatabase.proto

编译:生成grpcatabase_pb2.py grpcdatabase_pb2_grpc.py文件

python3 -m grpc_tools.protoc -I. --python_out=grpc_base_models/ --grpc_python_out=grpc_base_models/ grpcdatabase.proto


编写服务端代码:

# -*- coding: utf-8 -*-
# @author: chenhuachao
# @time: 2019/3/7
# Servers.py
import sys
sys.path.append('grpc_base_models')
import grpc
import time
from concurrent import futures
import grpcdatabase_pb2
import grpcdatabase_pb2_grpc
# from grpc_base_models import grpcdatabase_pb2
# from grpc_base_models import grpcdatabase_pb2_grpc

_SLEEP_TIME = 60
_HOST = "0.0.0.0"
_PORT = "19999"

class RpcServer(grpcdatabase_pb2_grpc.GreeterServicer):
    def GetContent(self, request, context):
        '''
        获取文章摘要
        :param request:
        :param context:
        :return:
        '''
        try:
            _content = request.content
            code = 0
        except Exception as e:
            _content = str(e)
            code=1
        return grpcdatabase_pb2.Return(message=_content,code=code)

def server():
    if sys.argv.__len__()>=2:
        _PORT = sys.argv[1]
    else:
        _PORT = "19999"
    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    grpcdatabase_pb2_grpc.add_GreeterServicer_to_server(RpcServer(), grpcServer)
    grpcServer.add_insecure_port("{0}:{1}".format(_HOST, _PORT))
    grpcServer.start()
    try:
        while True:
            time.sleep(_SLEEP_TIME)
    except KeyboardInterrupt:
        grpcServer.stop(0)

if __name__ == '__main__':
    server()

编写客户端代码:

# -*- coding: utf-8 -*-
# @author: chenhuachao
# @time: 2019/3/7
# Client.py
import sys
import grpc
sys.path.append('grpc_base_models')
import grpcdatabase_pb2_grpc
import grpcdatabase_pb2
# from grpc_base_models import grpcdatabase_pb2_grpc
# from grpc_base_models import grpcdatabase_pb2

# _HOST = '192.168.3.191'
_HOST = '127.0.0.1'
_PORT = '19999'

def RpcClient(funcname,content):
    '''
    rpc客户端程序
    :param funcname: 可用funcname为下面两个
        >>> GetContent  获取摘要, 参数:content='文本'
        *** 上面两个函数均返回message属性和code(1:failed 0:success)属性
        >>> 返回值:response.message   response.code
    :return:
    '''
    with grpc.insecure_channel("{0}:{1}".format(_HOST, _PORT)) as channel:
        client = grpcdatabase_pb2_grpc.GreeterStub(channel=channel)
        if hasattr(client,funcname):
            response = getattr(client,funcname)(grpcdatabase_pb2.Request(content=content))
        else:
            raise Exception(u"函数名错误")
    print("message=" , response.message)
    print( "code=",response.code)
if __name__ == '__main__':
    text = u'''
    测试的文本
    '''
    RpcClient('GetContent',text)

分别运行:Server.py 和Client.py 查看结果

上面服务端代码每次使用,都要依赖grpcdatabase_pb2*.py这两个文件,因此,我们可以打包为python模块。更加方便使用

打包

添加setup.py文件在根目录下:结构图

setup.py文件内容如下

# -*- coding: utf-8 -*-
# @author: chenhuachao
# @time: 2019/3/8
# setup.py

from setuptools import setup,find_packages
setup(
    name = "grpc_base_models",
    version = "0.0.1",
    keywords = ("pip", "pygrpc", "company", "chenhuachao"),
    description = "python版本的grpc公用模块,个人项目专用,仅供参考",
    long_description="grpc server for python",
    license="MIT Licence",
    url="https://github.com/leizhu900516",
    author="chenhuachao",
    author_email="[email protected]",
    packages = find_packages(),
    install_requires = [
        'grpcio==1.19.0',
        'grpcio-tools==1.19.0',
        'protobuf==3.7.0',
    ]
)

打包:
python3 setup.py sdist 如下图:

安装:pip install dist/grpc_base_models-0.0.1.tar.gz
即可在python脚本中使用
引用即可:

from grpc_base_models import grpcdatabase_pb2_grpc
from grpc_base_models import grpcdatabase_pb2

** 附上代码地址python版grpc实例

转载于:https://blog.51cto.com/leizhu/2359958

你可能感兴趣的:(python使用grpc,并打包成python模块)