1. 安装
python -m pip install grpcio #安装grpcpython -m pip install grpcio-tools #安装grpc tools
2. 先体验protobuf3
protobuf3 是有自己专门的定义格式的 - 门槛
syntax = "proto3";message HelloRequest {string name = 1;}
3. 生成proto的python文件
python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. helloworld.proto
4. 查看protobuf生成的代码
from grpc_test import helloworld_pb2request = helloworld_pb2.HelloRequest()request.name = "bobby"req_str = request.SerializeToString()print(req_str)request2 = helloworld_pb2.HelloRequest()request2.ParseFromString(req_str)print(request2.name)
5. 对比一下protobuf生成的效果
from grpc_test import helloworld_pb2request = helloworld_pb2.HelloRequest()request.name = "bobby"req_str = request.SerializeToString()print(req_str)import jsonreq_json = {"name":"bobby"}print(len(json.dumps(req_json)))print(len(req_str))
