以编程方式检查是否需要Google协议缓冲区字段

时间:2016-06-28 21:34:08

标签: python protocol-buffers

是否可以通过编程方式检查给定的原型字段是否标记为required vs optional?我正在使用python并且有一个FieldDescriptor对象,但找不到确定该字段是否必需的方法。

2 个答案:

答案 0 :(得分:3)

快速查看documentation表示您的FieldDescriptor应该有一个label属性,表明它是可选的,必需的还是重复的。

from google.protobuf.descriptor import FieldDescriptor

if fd.label == FieldDescriptor.LABEL_OPTIONAL:
    # do thing
elif fd.label == FieldDescriptor.LABEL_REQUIRED:
    # do other thing
else:
    # do third thing

答案 1 :(得分:1)

我知道这是一个老问题,但是我认为我的回答可以帮助某人。

我已经创建了一个递归函数,用于检查JSON格式的给定消息是否具有给定原型消息的所有必填字段。它还会检查嵌套消息的必填字段。

如您所见,label属性用于检查该字段是否为必填字段(已在可接受的答案中涵盖)。

def checkRequiredFields(protoMsg, jsonMsg, missingFields=[]):
    from google.protobuf.descriptor_pb2 import FieldDescriptorProto as fdp

    if hasattr(protoMsg, 'DESCRIPTOR'):
        for field in protoMsg.DESCRIPTOR.fields:
            if fdp.LABEL_REQUIRED == field.label:
                if field.name in jsonMsg:
                    newProtoMsg = getattr(protoMsg, field.name)
                    newJsonMsg = jsonMsg[field.name]
                    missingFields = __checkRequiredFields(newProtoMsg,
                                                          newJsonMsg,
                                                          missingFields)
                else:
                    missingFields.append(field.name)

    return missingFields

函数可以这样使用:

protoMsg = MyProtoMessage() # class generated from the proto files
jsonMsg = json.loads(rawJson) # message in a JSON format
missingFields = checkRequiredFields(protoMsg, jsonMsg)