一、场景
测试需要构造数据,而且存储的格式为grpc消息的二进制格式,所以必须要根据proto构造二进制
二、构造方法
1、根据proto文件生成python格式的pb文件
python3 -m grpc_tools.protoc -I. proto/upload_state.proto --python_out=. --grpc_python_out=.
2、检查文件生成
3、编写构造脚本
import base64 import json import pickle import redis import time import threading import concurrent.futuresfrom datetime import datetime from copy import deepcopyfrom google.protobuf.json_format import MessageToJsonimport upload_state_pb2 as upload_state_pb2data = {...... } def pack_data_proto_obj(vehicle, data_info_list):# 生成file_info_listfile_info_list_obj = upload_state_pb2.FileInfoList()file_info_list_obj.update_operation = "UPDATE"for data_info in data_info_list:data_info.append({"file_name": file_name,"file_type": data_info[0]["file_type"],......"del_flag": True})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_infovehicle_upload_info_obj = upload_state_pb2.VehicleUploadInfo()vehicle_upload_info_obj.vehicle = vehiclevehicle_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来组装
消息转换的方法MessageToJson,ParseFromString
参考链接:
proto与json的互相转换_proto转json-CSDN博客
Python 使用 Protobuf 的 message 嵌套,repeated 字段类型,google.protobuf.Any 字段类型,enum 枚举字段_protobuf repeated enum-CSDN博客
Python的基本Protobuf指南(序列化数据) - DaisyLinux - 博客园