无法在Python中反序列化protobuf二进制文件(由Nodejs创建)

2024-05-23 20:01:26 发布

您现在位置:Python中文网/ 问答频道 /正文

请查看以下上下文并帮助解决此问题

我在device.proto中定义了以下消息

message DeviceConfiguration {
  message Resolution {
    uint32 width = 1;
    uint32 height = 2;
  }
  string device_name = 1;
  string brand_name = 2;
  Resolution resolution = 3;
}

然后,将此消息编译成两种语言:Nodejs(device_pb.js)和Python(device_pb2.py)

1。来自Nodejs:将上述消息发送给卡夫卡

const {DeviceConfiguration} = require("./device_pb")

const resolution = new DeviceConfiguration.Resolution();
resolution.setWidth(1280);
resolution.setHeight(960);

const deviceConfiguration = new DeviceConfiguration();
deviceConfiguration.setDeviceName("S6");
deviceConfiguration.setBrandName("samsung");
deviceConfiguration.setResolution(resolution);

let binaryEvent = deviceConfiguration.serializeBinary();

最后,使用Kafka节点向Kafka主题发送binaryEvent

2。来自Python组件:通过kafka使用消息

  • 下面是python组件中接收到的二进制值

b'10,8,111,98,106,101,99,116,73,100,26,21,10,2,83,54,18,7,115,97,109,115,117,110,103,26,6,8,128,10,16,192,7'

  • 然后,我使用下面的代码反序列化消息,但它抛出一条消息“错误解析消息”

    从设备_pb2导入设备配置

    设备=设备配置()

    device.ParseFromString(消息)

=>;正如我看到的,ParseFromString不适用于上述二进制值,并抛出“错误解析消息”。只有当字节值是由SerializeToStringpython代码创建时,它才起作用

注意:我可以在Nodejs中使用反序列化二进制文件(公开)来反序列化二进制文件,但在device_pb2.py中没有类似的功能

那么,我有没有办法用Python代码反序列化消息?

非常感谢


Tags: 代码消息messagestring序列化devicenodejs二进制