Python中Protobuf的基本使用
文章目录
1. 创建proto文件
-
example.proto
syntax = "proto2"; package example; message ExampleRequest { optional int32 type = 1; repeated int32 list = 2; } message ExampleReply { optional int32 ret = 1; optional string err_msg = 2; repeated Item items = 3; } message Item { optional string name = 1; }
2. 生成py文件
protoc --python_out=. example.proto
# 会生成example_pb2.py文件
3. message与json、dict互转
直接看代码
import example_pb2 as pb
import google.protobuf.json_format as json_format
# dict转message
request = {
"type": 1,
"list": [1, 2, 3]
}
exampleReq = json_format.ParseDict(request, pb.ExampleRequest())
print(exampleReq)
# json转message
reqJson = '{"type": 2, "list": [4, 5, 6]}'
exampleReq = json_format.Parse(reqJson, pb.ExampleRequest())
print(exampleReq)
# message转json
print("json: {0}".format(json_format.MessageToJson(exampleReq)))
# message转dict
print("dict: {0}".format(json_format.MessageToDict(exampleReq)))
4. message与二进制字节流互转
# message转binary
binary = exampleReq.SerializeToString()
print("binary:{0}".format(binary))
# binary转message
msg = pb.ExampleRequest()
msg.ParseFromString(binary)
print("msg: {}".format(msg))
5. message其他操作
# 合并两个message
exampleReq.MergeFrom(exampleReq1)
print("merge message: {}".format(exampleReq))
# copy message
exampleReq.CopyFrom(exampleReq1)
print("copy message: {}".format(exampleReq))
6 message直接赋值与读取
# 直接赋值
req2 = pb.ExampleRequest()
req2.type = 1
req2.list.extend([1, 2, 3])
print("req2:{}".format(req2))
# 读取
req3 = pb.ExampleRequest()
req3.type = req2.type
# req3.list = req2.list, 这样是错误的
req3.list.extend(req2.list) # 这样
print("req3:{}".format(req3))