1. 安装

  1. python -m pip install grpcio #安装grpc
  2. python -m pip install grpcio-tools #安装grpc tools

2. 先体验protobuf3

protobuf3 是有自己专门的定义格式的 - 门槛

  1. syntax = "proto3";
  2. message HelloRequest {
  3. string name = 1;
  4. }

3. 生成proto的python文件

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

4. 查看protobuf生成的代码

  1. from grpc_test import helloworld_pb2
  2. request = helloworld_pb2.HelloRequest()
  3. request.name = "bobby"
  4. req_str = request.SerializeToString()
  5. print(req_str)
  6. request2 = helloworld_pb2.HelloRequest()
  7. request2.ParseFromString(req_str)
  8. print(request2.name)

5. 对比一下protobuf生成的效果

  1. from grpc_test import helloworld_pb2
  2. request = helloworld_pb2.HelloRequest()
  3. request.name = "bobby"
  4. req_str = request.SerializeToString()
  5. print(req_str)
  6. import json
  7. req_json = {
  8. "name":"bobby"
  9. }
  10. print(len(json.dumps(req_json)))
  11. print(len(req_str))