美文网首页
谷歌Protobuf python教程1快速入门

谷歌Protobuf python教程1快速入门

作者: python测试开发 | 来源:发表于2021-02-04 11:00 被阅读0次

起因

google的官方文档和国内多数文档把Protobuf介绍得过于复杂,对于部分初学者不方便上手,为此写了这个由浅入深的教程。

安装

以ubuntu 20.04为例

# apt  install protobuf-compiler
# pip install protobuf

快速上手

谷歌Protobuf是一种快速有效地将结构化数据序列化为二进制数据流的方法,它被设计用于机器间通信和远程过程调用(RPC)。它被设计用于机器间通信和远程过程调用(RPC remote procedure calls )。

  • 定义协议文件 metric.proto
message Metric {
  required string name = 1;
  required string type = 2;
  required float value = 3;
  repeated string tags = 4;
}
  • 生成python协议代码
$ protoc --python_out=. metric.proto
[libprotobuf WARNING google/protobuf/compiler/parser.cc:562] No syntax specified for the proto file: metric.proto. Please use 'syntax = "proto2";' or 'syntax = "proto3";' to specify a syntax version. (Defaulted to proto2 syntax.)
$ ls metric*.py
metric_pb2.py

可以看到已经生成文件metric_pb2.py,里面的内容通常不需要关心。

  • 序列化
import metric_pb2

my_metric = metric_pb2.Metric()
my_metric.name = 'sys.cpu'
my_metric.type = 'gauge'
my_metric.value = 99.9
my_metric.tags.extend(['my_tag', 'foo:bar'])

with open('out.bin', 'wb') as f:
    f.write(my_metric.SerializeToString())

上面的代码将protobuf流写入磁盘上的二进制文件out.bin。

  • 反序列化
import metric_pb2

with open('out.bin', 'rb') as f:
    read_metric = metric_pb2.Metric()
    read_metric.ParseFromString(f.read())
    
print(read_metric)

执行结果:

$ python pb_unpack.py 
name: "sys.cpu"
type: "gauge"
value: 99.9000015258789
tags: "my_tag"
tags: "foo:bar"

相关文章

网友评论

      本文标题:谷歌Protobuf python教程1快速入门

      本文链接:https://www.haomeiwen.com/subject/svtbtltx.html