1、编辑 proto 文件

syntax = "proto3";

package proto;

service GeekAuth {
    // 获取目标权限树
    rpc Tree(TreeReq) returns (TreeRsp){};
}

// 获取目标权限树 请求参数
message TreeReq {
    string appKey = 1;                // 字符串类型,参数名为 appKey
    string secretKey = 2;
    int64 target  = 3;                  //  整型,参数名为 target
    repeated int64 authId = 4;    // 数组类型,数组内元素类型为整型
}    

// 获取目标权限树 返回内容 
message TreeRsp {
    int64 code = 1;
    string message = 2;
    string data = 3;            //  data 为 json 字符串
}
demo.proto

 

 

2、编译 proto 文件

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

# 编译后会在当前目录下生成两个文件:demo_pb2.py, demo_pb2_grpc.py

 

3、使用

import grpc
from . import demo_pb2, demo_pb2_grpc


channel = grpc.insecure_channel("127.0.0.1:9999") stub = demo_pb2_grpc.GeekAuthStub(channel) # 注意:当 proto 文件中规定参数类型是 string 时,在python代码使用时需要对参数进行编码 response = stub.Tree(demo_pb2.TreeReq(appKey=AppKey.encode(), secretKey=SecretKey.encode(), target=user_data.u_id))
data = json.loads(response.data)

 

 posted on 2020-08-19 17:14  lin-gooo  阅读(299)  评论(0编辑  收藏  举报