1. 环境准备
grpc相关库安装
pip install grpcio grpcio-tools
定义服务:使用protocolbuffers/protobuf格式来创建结构化数据文件xxx.proto,内容如下:
syntax = "proto3";
option cc_generic_services = true;
service GrpcAuthService {
rpc Authorization(GrpcAuthoRequest) returns (GrpcAuthResult);
}
message GrpcAuthoRequest {
string authorization = 1;
}
message GrpcAuthResult {
int32 code = 1;
string userCode = 2;
string userId = 3;
bool success = 4;
string msg = 5;
int32 status = 6;
}
上面我们定义了一个鉴权的方法,根据上面定义是生成python代码:
python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. xxx.proto
客户端
def verifyAuth(request: Request, response: Response):
authorization = request.headers["Authorization"]
channel = grpc.insecure_channel(config.auth_url)
requestData = auth_pb2.GrpcAuthoRequest(authorization=authorization)
stub = auth_pb2_grpc.GrpcAuthServiceStub(channel)
res = stub.Authorization(requestData)
if not res.success:
raise NormalException(401, res.code, res.msg)
return
注意:grpcio-tools如果版本大于1.43.0,则生成的方法会在运行中动态生成,这样就无法使用pychram的语法提示了,所以可以将版本回滚到1.43.0及其之前的版本