温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python使用grpc并打包成python模块的方法

发布时间:2021-08-21 22:19:52 来源:亿速云 阅读:178 作者:chen 栏目:编程语言

本篇内容介绍了“python使用grpc并打包成python模块的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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

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

pip3 install grpcio
pip3 install protobuf
pip3 install grpcio-tools

三、准备grpc配置文件grpcdatabase.proto
目录结构:
python使用grpc并打包成python模块的方法
内容如下:

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

python使用grpc并打包成python模块的方法
编写服务端代码:

# -*- 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 查看结果
python使用grpc并打包成python模块的方法

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

打包

添加setup.py文件在根目录下:结构图
python使用grpc并打包成python模块的方法
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="leizhu900516@163.com",
    packages = find_packages(),
    install_requires = [
        'grpcio==1.19.0',
        'grpcio-tools==1.19.0',
        'protobuf==3.7.0',
    ]
)

打包:
python3 setup.py sdist     如下图:
python使用grpc并打包成python模块的方法
安装: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并打包成python模块的方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI