【grpc】根据proto生成grpc接口Python代码

发布时间 2023-03-22 21:08:59作者: 代码诠释的世界

 

1、编写自己的proto接口文件

syntax = "proto3";

package helloworld;  // 对应包名

// 定义服务
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {
  // 插件内容
  }
}

// 客户端传的名字
message HelloRequest {
  string name = 1;
}

// 服务端返回的消息
message HelloReply {
  string message = 1;
}

 


2.安装protobuf编译器和grpc库

pip install grpcio-tools
pip install protobuf

 

3.编译生成代码

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto


参数解释:
-I 表示搜索proto文件中被导入文件的目录 . 代表当前目录
--python_out 表示保存生成Python文件的目录,生成的文件中包含接口定义中的<数据message>类型
--grpc_python_out 表示保存生成Python文件的目录,生成的文件中包含接口定义中的<服务service>类型

在目录下执行上述命令,会自动生成如下两个rpc调用辅助代码模块:
helloworld_pb2.py 保存根据接口定义文件中的<数据message>类型生成的python类
helloworld_pb2_grpc.py 保存根据接口定义文件中的<服务service>方法类型生成的python调用RPC方法

 

3、编写服务端和客户端代码

# 创建服务端代码 service.py
from concurrent import futures
import time
import grpc
import helloworld_pb2
import helloworld_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class Greeter(helloworld_pb2_grpc.GreeterServicer):
    # 工作函数
    def SayHello(self, request, context):
        print(request.name)
        message = "This message is from Server.And what i want to say is hello \" " + request.name + " \"";
        return helloworld_pb2.HelloReply(message = message)


def serve():
    # gRPC 服务器
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    print("sever is opening ,waiting for message...")
    server.start()  # start() 不会阻塞,如果运行时你的代码没有其它的事情可做,你可能需要循环等待。
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

# 创建客户端代码 client.py
from __future__ import print_function

import grpc

import helloworld_pb2
import helloworld_pb2_grpc


def run():
    channel = grpc.insecure_channel('localhost:50051')
    stub = helloworld_pb2_grpc.GreeterStub(channel)
    response = stub.SayHello(helloworld_pb2.HelloRequest(name='Hello World! This is message from client!'))
    print("Greeter client received: " + response.message)


if __name__ == '__main__':
    run()

 

4、调用

先运行service代码,再执行Python代码