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

Programatically check if google protocol buffer field is required

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

快速查看 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

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

我创建了一个递归函数,用于检查 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)