【proto】python根據proto檔案構造message,並換為二進位制

代码诠释的世界發表於2024-07-09

一、場景

測試需要構造資料,而且儲存的格式為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 - 部落格園

相關文章