如何访问未知字段 - python protobuf [英] How to access unknown fields - python protobuf

查看:55
本文介绍了如何访问未知字段 - python protobuf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理大量具有相似但不同结构的消息类型.所有这些中常见的东西都在另一条消息中.当消息传入时,我使用通用消息类型对其进行解析.但是,我似乎无法找到访问此类型之外的字段(即非常见字段)的方法.有没有办法访问python中设置的未知字段?

我刚刚在文档中看到了这一点:

"如果消息有未知字段,当前的 Java 和 C++ 实现会在按顺序排列的已知字段之后以任意顺序写入它们.当前的 Python 实现不会跟踪未知字段.">

这是否意味着如果我使用通用类型进行解析,例如:

proto = msg_pb2.Common()proto.ParseFromString(raw_msg)

是否会丢弃消息 Common 中未定义的任何字段?

解决方案

对于寻求答案的人来说,reflection 模块帮助了我:https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.reflection-module

相关示例代码:

示例用法:

file_descriptor = descriptor_pb2.FileDescriptorProto()file_descriptor.ParseFromString(proto2_string)msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])msg_class = 反射.MakeClass(msg_descriptor)msg = msg_class()参数:描述符:描述protobuf的descriptor.Descriptor对象.返回:描述符描述的 Message 类对象.

I am working with a large number of message types with similar but not identical structure. All the stuff that's common among these is in another message. When a message comes in, I parse it using the common message type. However, I can't seem to find a way to access the fields outside of this type (i.e. the non-common fields). Is there a way to access the unknown field set in python?

Edit: I just saw this in the documentation:

"If a message has unknown fields, the current Java and C++ implementations write them in arbitrary order after the sequentially-ordered known fields. The current Python implementation does not track unknown fields."

Does this mean that if I parse using the common type, eg:

proto = msg_pb2.Common() proto.ParseFromString(raw_msg)

Any fields not defined in message Common are thrown away?

解决方案

To someone looking for an answer to this, the reflection module helped me: https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.reflection-module

The relevant sample code:

Sample usage:

file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(proto2_string)   
msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
msg_class = reflection.MakeClass(msg_descriptor)
msg = msg_class()

Args:
   descriptor: A descriptor.Descriptor object describing the protobuf.
Returns:
   The Message class object described by the descriptor.

这篇关于如何访问未知字段 - python protobuf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆