python 提供gRPC服务

最近学习了python 如何提供gRPC 服务, 这里以官方教程 和博客 为参考,简单记录一下具体步骤

0. 安装相关依赖包:grpcio、protobuf、grpcio-tools

1. 定义proto文件, 这里命名为`hello.proto` 

syntax = "proto3";

package hello;

//定义服务接口
service GrpcService {
    rpc hello (HelloRequest) returns (HelloResponse) {}  //一个服务中可以定义多个接口,也就是多个函数功能
}

//请求的参数
message HelloRequest {
    string data = 1;   //数字1,2是参数的位置顺序,并不是对参数赋值
    Skill skill = 2;  //支持自定义的数据格式,非常灵活
};

//返回的对象
message HelloResponse {
    string result = 1;
    map<string, int32> map_result = 2; //支持map数据格式,类似dict
};

message Skill {
    string name = 1;
};

2. 编译步骤1中生成的proto文件,-I 指定proto所在目录, 编译成功之后,在python_out指定的路径会生成addressbook_pb2.py文件, 在grpc_python_out指定的路径会生成addressbook_pb2_grpc.py文件 

python -m grpc_tools.protoc -I=./ --python_out=./ --grpc_python_out=./ ./hello.proto

3. 在Python中实现服务接口,定义如下`server.py`

import time
from concurrent import futures

import grpc

import hello_pb2_grpc, hello_pb2



class TestService(hello_pb2_grpc.GrpcServiceServicer):
    '''
    继承GrpcServiceServicer,实现hello方法
    '''
    def __init__(self):
        pass

    def hello(self, request, context):
        '''
        具体实现hello的方法,并按照pb的返回对象构造HelloResponse返回
        :param request:
        :param context:
        :return:
        '''
        result = request.data + request.skill.name + " this is gprc hello service"
        list_result = {"12": 1232}
        return hello_pb2.HelloResponse(result=str(result),
                                       map_result=list_result)


def run():
    '''
    模拟服务启动
    :return:
    '''
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))

    hello_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)
    server.add_insecure_port('[::]:50051')
    server.start()
    print("start grpc service...")
    server.wait_for_termination()


if __name__ == '__main__':
    run()

成功运行server.py之后,可以再定义个client.py来测试是否调通服务

import grpc
import hello_pb2_grpc, hello_pb2


def run():
    '''
    模拟请求服务方法信息
    :return:
    '''
    conn=grpc.insecure_channel('127.0.0.1:50051')
    client = hello_pb2_grpc.GrpcServiceStub(channel=conn)
    skill = hello_pb2.Skill(name="coding")
    request = hello_pb2.HelloRequest(data="hello grpc", skill=skill)
    response = client.hello(request)
    print("received:",response.result)


if __name__ == '__main__':
    run()

运行client.py 将会打印出如下结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值