How to access unknown fields - python protobuf

爷,独闯天下 提交于 2021-02-10 14:42:12

问题


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?


回答1:


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.


来源:https://stackoverflow.com/questions/32897438/how-to-access-unknown-fields-python-protobuf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!