Protobuf

image-20240517210405562

protobuf是Google公司提出的一种轻便高效的结构化数据存储格式,常用于结构化数据的序列化,具有语言无关、平台无关、可扩展性特性,常用于通讯协议、服务端数据交换场景。

1.下载安装

1.1 Windows

https://github.com/protocolbuffers/protobuf/releases

image-20240517210414986

image-20240517210422714

image-20240517210429095

image-20240517210437203

1.2 Mac

1
brew install protobuf@3

如果电脑未安装brew,则请先去安装:

1
2
>>>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
>>>brew --version

image-20240517210446057

image-20240517210452021

将目录加入环境变量:

1
2
PATH="/usr/local/opt/[email protected]/bin:${PATH}"
export PATH

image-20240517210500738

2.Pycharm插件

image-20240517210506162

3.定义数据结构

官方文档:https://developers.google.com/protocol-buffers/docs/pythontutorial

1
2
3
4
5
6
7
8
9
10
11
12
13
syntax = "proto3";

package wupeiqi;

message Person {
string name = 1;
int32 age = 2;
}

message Message {
string method = 1;
string payload = 2;
}

image-20240517210514376

6.转换Python版本

在命令行执行:

1
protoc  --python_out=.   v1.proto

image-20240517210523114

7.Python操作模块

1
pip install protobuf

image-20240517210530159

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from google.protobuf import json_format

# 1.创建对象转换成字节,用于后续网络传输(序列化)
from v1_pb2 import Person, Message

p1 = Person()
p1.name = "wupeiqi"
p1.age = 19

info = p1.SerializeToString()
print(info)

p2 = Message()
p2.method = "POST"
p2.payload = "太NB了"
info = p2.SerializeToString()
print(info)

# 2.根据字节转化对象,用于业务处理(反序列化)
obj = Message()
obj.ParseFromString(info)
print(obj.method)
print(obj.payload)


# 3.对象转字典
from google.protobuf import json_format

data_dict = json_format.MessageToDict(obj)
print(data_dict, type(data_dict))

data_string = json_format.MessageToJson(obj,ensure_ascii=False)
print(data_string, type(data_string))

__END__