【proto】python根据proto文件构造message,并换为二进制

一、场景

    测试需要构造数据,而且存储的格式为grpc消息的二进制格式,所以必须要根据proto构造二进制

 

二、构造方法

1、根据proto文件生成python格式的pb文件

python3 -m grpc_tools.protoc -I. proto/upload_state.proto --python_out=. --grpc_python_out=.

 

2、检查文件生成

 

3、编写构造脚本

复制代码
from google.protobuf.json_format import MessageToJson

import upload_state_pb2 as upload_state_pb2

def pack_data_proto_obj(vehicle, data_info_list):
    # 生成file_info_list
    file_info_list_obj = upload_state_pb2.FileInfoList()
    file_info_list_obj.update_operation = "UPDATE"
    for data_info in data_info_list:for index in range(len(data_info)):
            # 生成file_info对象
            file_info_obj = upload_state_pb2.FileInfo()
            file_info_obj.file_name = data_info[index]["file_name"].replace("vehicle", vehicle)
            file_info_obj.file_type = data_info[index]["file_type"]
......
file_info_obj.del_flag = data_info[index]["del_flag"] file_info_list_obj.file_infos.append(file_info_obj) # 生成vehicle_upload_info vehicle_upload_info_obj = upload_state_pb2.VehicleUploadInfo() vehicle_upload_info_obj.vehicle = vehicle vehicle_upload_info_obj.msg_type = data["msg_type"] vehicle_upload_info_obj.file_info_list.CopyFrom(file_info_list_obj) proto_data = vehicle_upload_info_obj.SerializeToString() print(proto_data) vehicle_upload_info_obj2 = upload_state_pb2.VehicleUploadInfo() vehicle_upload_info_obj2.ParseFromString(proto_data) json_string = MessageToJson(vehicle_upload_info_obj2) print(json_string) return proto_data # 转proto字符串 # vehicle_upload_info_obj1 = upload_state_pb2.VehicleUploadInfo() # vehicle_upload_info_obj1.ParseFromString(proto_data) # print(vehicle_upload_info_obj1)

vehicle_upload_info_obj2 = upload_state_pb2.VehicleUploadInfo()
vehicle_upload_info_obj2.ParseFromString(proto_data)
json_string = MessageToJson(vehicle_upload_info_obj2)
print(json_string)

if __name__ == '__main__': pass
复制代码

内容省略,主要是三层message嵌套

关键点就是append和CopyFrom来组装

消息转换的方法MessageToJsonParseFromString

 

 

 

参考链接:

proto与json的互相转换_proto转json-CSDN博客

Python 使用 Protobuf 的 message 嵌套,repeated 字段类型,google.protobuf.Any 字段类型,enum 枚举字段_protobuf repeated enum-CSDN博客

Python的基本Protobuf指南(序列化数据) - DaisyLinux - 博客园

posted @   代码诠释的世界  阅读(119)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示