如何访问未知字段
我正在处理大量类似但结构不相同的消息类型。 所有这些常见的东西都在另一个消息中。 当消息进入时,我使用常用消息类型对其进行解析。 但是,我似乎无法找到访问此类型以外的字段(即非公共字段)的方法。 有没有办法访问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 = 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.
链接地址: http://www.djcxy.com/p/77285.html
上一篇: How to access unknown fields
下一篇: c++ protobuf: how to iterate through fields of message?