Python google.protobuf.descriptor.FieldDescriptor.TYPE_ENUM() Examples

The following are code examples for showing how to use google.protobuf.descriptor.FieldDescriptor.TYPE_ENUM(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: grpc-django   Author: soheltarir   File: protobuf_to_dict.py    MIT License 6 votes vote down vote up
def _get_field_value_adaptor(pb, field, type_callable_map=TYPE_CALLABLE_MAP, use_enum_labels=False,
                             including_default_value_fields=False):
    if field.message_type and field.message_type.name == Timestamp_type_name:
        return timestamp_to_datetime
    if field.type == FieldDescriptor.TYPE_MESSAGE:
        # recursively encode protobuf sub-message
        return lambda pb: protobuf_to_dict(
            pb, type_callable_map=type_callable_map,
            use_enum_labels=use_enum_labels,
            including_default_value_fields=including_default_value_fields,
        )

    if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM:
        return lambda value: enum_label_name(field, value)

    if field.type in type_callable_map:
        return type_callable_map[field.type]

    raise TypeError("Field %s.%s has unrecognised type id %d" % (
        pb.__class__.__name__, field.name, field.type)) 
Example 2
Project: sea   Author: shanbay   File: format.py    MIT License 6 votes vote down vote up
def _get_field_value_adaptor(pb, field, use_enum_labels,
                             including_default_value_fields):
    if field.type == FieldDescriptor.TYPE_MESSAGE:
        # recursively encode protobuf sub-message
        return lambda pb: msg2dict(
            pb, use_enum_labels=use_enum_labels,
            including_default_value_fields=including_default_value_fields)

    if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM:
        return lambda value: enum_label_name(field, value)

    if field.type in TYPE_CALLABLE_MAP:
        return TYPE_CALLABLE_MAP[field.type]

    raise TypeError("Field %s.%s has unrecognised type id %d" % (
        pb.__class__.__name__, field.name, field.type)) 
Example 3
Project: python-cf-api   Author: hsdp   File: pb2dict.py    Apache License 2.0 6 votes vote down vote up
def _get_field_value_adaptor(pb, field, type_callable_map=TYPE_CALLABLE_MAP, use_enum_labels=False,
                             including_default_value_fields=False, lowercase_enum_lables=False):

    if field.message_type and field.message_type.name == Timestamp_type_name:
        return timestamp_to_datetime
    if field.type == FieldDescriptor.TYPE_MESSAGE:
        # recursively encode protobuf sub-message
        return lambda pb: protobuf_to_dict(
            pb, type_callable_map=type_callable_map,
            use_enum_labels=use_enum_labels,
            including_default_value_fields=including_default_value_fields,
            lowercase_enum_lables=lowercase_enum_lables,
        )

    if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM:
        return lambda value: enum_label_name(field, value, lowercase_enum_lables)

    if field.type in type_callable_map:
        return type_callable_map[field.type]

    raise TypeError("Field %s.%s has unrecognised type id %d" % (
        pb.__class__.__name__, field.name, field.type)) 
Example 4
Project: idasec   Author: RobinDavid   File: protobuf_json.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def json2pb(pb, js):
    """ convert JSON string to google.protobuf.descriptor instance
    :param pb: protobuf class to fill
    :param js: json input data
    """
    for field in pb.DESCRIPTOR.fields:
        if field.name not in js:
            continue
        if field.type == FD.TYPE_MESSAGE:
            pass
        elif field.type in _js2ftype:
            ftype = _js2ftype[field.type]
        else:
            raise ParseError(
                "Field %s.%s of type '%d' is not supported" % (pb.__class__.__name__, field.name, field.type,))
        value = js[field.name]
        if field.label == FD.LABEL_REPEATED:
            pb_value = getattr(pb, field.name, None)
            for v in value:
                if field.type == FD.TYPE_MESSAGE:
                    json2pb(pb_value.add(), v)
                else:
                    pb_value.append(ftype(v))
        else:
            if field.type == FD.TYPE_MESSAGE:
                json2pb(getattr(pb, field.name, None), value)
            elif field.type == FD.TYPE_ENUM:
                real_value = field.enum_type.values_by_name[value].number
                setattr(pb, field.name, real_value)
            else:
                setattr(pb, field.name, ftype(value))
    return pb 
Example 5
Project: idasec   Author: RobinDavid   File: protobuf_json.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def pb2json(pb):
    """ convert google.protobuf.descriptor instance to JSON string
    :param pb: protobuf class to be converted in json
    """
    js = {}
    # fields = pb.DESCRIPTOR.fields #all fields
    fields = pb.ListFields()  # only filled (including extensions)
    for field, value in fields:
        if field.type == FD.TYPE_MESSAGE:
            ftype = pb2json
        elif field.type == FD.TYPE_ENUM:
            ftype = str
            value = field.enum_type.values_by_number[value].name
        elif field.type in _ftype2js:
            ftype = _ftype2js[field.type]
        else:
            raise ParseError(
                "Field %s.%s of type '%d' is not supported" % (pb.__class__.__name__, field.name, field.type,))
        if field.label == FD.LABEL_REPEATED:
            js_value = []
            for v in value:
                js_value.append(ftype(v))
        else:
            js_value = ftype(value)
        js[field.name] = js_value
    return js 
Example 6
Project: randomproto   Author: yupingso   File: randomproto.py    MIT License 5 votes vote down vote up
def _fill_random(msg, desc):
    """Fill all fields of ``msg`` with random values."""
    for field in desc.fields:
        is_message = field.type == FieldDescriptor.TYPE_MESSAGE
        is_repeated = field.label == FieldDescriptor.LABEL_REPEATED
        if is_message:
            msg_field = getattr(msg, field.name)
            if is_repeated:
                num = random.randint(0, 2)
                for _ in range(num):
                    element = msg_field.add()
                    _fill_random(element, field.message_type)
            else:
                _fill_random(msg_field, field.message_type)
        else:
            if field.type == FieldDescriptor.TYPE_ENUM:
                enum_values = [x.number for x in field.enum_type.values]
                generator = functools.partial(random.choice, enum_values)
            else:
                generator = _FIELD_RANDOM_GENERATOR.get(field.type)
            if is_repeated:
                num = random.randint(0, 2)
                msg_field = getattr(msg, field.name)
                for _ in range(num):
                    msg_field.append(generator())
            else:
                setattr(msg, field.name, generator()) 
Example 7
Project: perceptron-benchmark   Author: advboxes   File: protobuf_to_dict.py    Apache License 2.0 5 votes vote down vote up
def _get_field_value_adaptor(pb, field, type_callable_map=TYPE_CALLABLE_MAP, use_enum_labels=False):
    if field.type == FieldDescriptor.TYPE_MESSAGE:
        # recursively encode protobuf sub-message
        return lambda pb: protobuf_to_dict(pb, type_callable_map, use_enum_labels)

    if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM:
        return lambda value: enum_label_name(field, value)

    if field.type in type_callable_map:
        return type_callable_map[field.type]

    raise TypeError("Field %s.%s has unrecognised type id %d" % (
        pb.__class__.__name__, field.name, field.type)) 
Example 8
Project: perceptron-benchmark   Author: advboxes   File: protobuf_to_dict.py    Apache License 2.0 5 votes vote down vote up
def _dict_to_protobuf(pb, value, type_callable_map, strict):
    """ dict to protobuf

    Args:
        pb: data in dict format

    Returns:
        pb: data in proto format
    """

    fields = _get_field_mapping(pb, value, strict)

    for field, input_value, pb_value in fields:
        if field.label == FieldDescriptor.LABEL_REPEATED:
            for item in input_value:
                if field.type == FieldDescriptor.TYPE_MESSAGE:
                    m = pb_value.add()
                    _dict_to_protobuf(m, item, type_callable_map, strict)
                elif field.type == FieldDescriptor.TYPE_ENUM and isinstance(item, basestring):
                    pb_value.append(_string_to_enum(field, item))
                else:
                    pb_value.append(item)
            continue
        if field.type == FieldDescriptor.TYPE_MESSAGE:
            _dict_to_protobuf(pb_value, input_value, type_callable_map, strict)
            continue

        if field.type in type_callable_map:
            input_value = type_callable_map[field.type](input_value)

        if field.is_extension:
            pb.Extensions[field] = input_value
            continue

        if field.type == FieldDescriptor.TYPE_ENUM and isinstance(input_value, basestring):
            input_value = _string_to_enum(field, input_value)

        setattr(pb, field.name, input_value)

    return pb 
Example 9
Project: pogom-updated   Author: PokeHunterProject   File: protobuf_to_dict.py    MIT License 5 votes vote down vote up
def _get_field_value_adaptor(pb, field, type_callable_map=TYPE_CALLABLE_MAP, use_enum_labels=False):
    if field.type == FieldDescriptor.TYPE_MESSAGE:
        # recursively encode protobuf sub-message
        return lambda pb: protobuf_to_dict(
            pb, type_callable_map=type_callable_map,
            use_enum_labels=use_enum_labels)

    if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM:
        return lambda value: enum_label_name(field, value)

    if field.type in type_callable_map:
        return type_callable_map[field.type]

    raise TypeError("Field %s.%s has unrecognised type id %d" % (
        pb.__class__.__name__, field.name, field.type)) 
Example 10
Project: pogom-updated   Author: PokeHunterProject   File: protobuf_to_dict.py    MIT License 5 votes vote down vote up
def _dict_to_protobuf(pb, value, type_callable_map, strict):
    fields = _get_field_mapping(pb, value, strict)

    for field, input_value, pb_value in fields:
        if field.label == FieldDescriptor.LABEL_REPEATED:
            if field.message_type and field.message_type.has_options and field.message_type.GetOptions().map_entry:
                pb_value.update(input_value)
                continue
            for item in input_value:
                if field.type == FieldDescriptor.TYPE_MESSAGE:
                    m = pb_value.add()
                    _dict_to_protobuf(m, item, type_callable_map, strict)
                elif field.type == FieldDescriptor.TYPE_ENUM and isinstance(item, six.string_types):
                    pb_value.append(_string_to_enum(field, item))
                else:
                    pb_value.append(item)
            continue
        if field.type == FieldDescriptor.TYPE_MESSAGE:
            _dict_to_protobuf(pb_value, input_value, type_callable_map, strict)
            continue

        if field.type in type_callable_map:
            input_value = type_callable_map[field.type](input_value)

        if field.is_extension:
            pb.Extensions[field] = input_value
            continue

        if field.type == FieldDescriptor.TYPE_ENUM and isinstance(input_value, six.string_types):
            input_value = _string_to_enum(field, input_value)

        setattr(pb, field.name, input_value)

    return pb 
Example 11
Project: grpc-django   Author: soheltarir   File: protobuf_to_dict.py    MIT License 4 votes vote down vote up
def _dict_to_protobuf(pb, value, type_callable_map, strict, ignore_none):
    fields = _get_field_mapping(pb, value, strict)

    for field, input_value, pb_value in fields:
        if ignore_none and input_value is None:
            continue
        if field.label == FieldDescriptor.LABEL_REPEATED:
            if field.message_type and field.message_type.has_options and field.message_type.GetOptions().map_entry:
                value_field = field.message_type.fields_by_name['value']
                for key, value in input_value.items():
                    if value_field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
                        _dict_to_protobuf(getattr(pb, field.name)[key], value, type_callable_map, strict, ignore_none)
                    else:
                        getattr(pb, field.name)[key] = value
                continue
            for item in input_value:
                if field.type == FieldDescriptor.TYPE_MESSAGE:
                    m = pb_value.add()
                    _dict_to_protobuf(m, item, type_callable_map, strict, ignore_none)
                elif field.type == FieldDescriptor.TYPE_ENUM and isinstance(item, six.string_types):
                    pb_value.append(_string_to_enum(field, item))
                else:
                    pb_value.append(item)
            continue
        if isinstance(input_value, datetime.datetime):
            input_value = datetime_to_timestamp(input_value)
            # Instead of setattr we need to use CopyFrom for composite fields
            # Otherwise we will get AttributeError: Assignment not allowed to composite field “field name” in protocol message object
            getattr(pb, field.name).CopyFrom(input_value)
            continue
        elif field.type == FieldDescriptor.TYPE_MESSAGE:
            _dict_to_protobuf(pb_value, input_value, type_callable_map, strict, ignore_none)
            continue

        if field.type in type_callable_map:
            input_value = type_callable_map[field.type](input_value)

        if field.is_extension:
            pb.Extensions[field] = input_value
            continue

        if field.type == FieldDescriptor.TYPE_ENUM and isinstance(input_value, six.string_types):
            input_value = _string_to_enum(field, input_value)
        # Handle tri bool enum field
        if field.type == FieldDescriptor.TYPE_ENUM and type(input_value) == bool:
            if input_value is True:
                input_value = 1
            elif input_value is False:
                input_value = 2
            else:
                input_value = 0

        setattr(pb, field.name, input_value)

    return pb 
Example 12
Project: python-cf-api   Author: hsdp   File: pb2dict.py    Apache License 2.0 4 votes vote down vote up
def _dict_to_protobuf(pb, value, type_callable_map, strict, ignore_none):
    fields = _get_field_mapping(pb, value, strict)

    for field, input_value, pb_value in fields:
        if ignore_none and input_value is None:
            continue
        if field.label == FieldDescriptor.LABEL_REPEATED:
            if field.message_type and field.message_type.has_options and field.message_type.GetOptions().map_entry:
                value_field = field.message_type.fields_by_name['value']
                for key, value in input_value.items():
                    if value_field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
                        _dict_to_protobuf(getattr(pb, field.name)[key], value, type_callable_map, strict, ignore_none)
                    else:
                        getattr(pb, field.name)[key] = value
                continue
            for item in input_value:
                if field.type == FieldDescriptor.TYPE_MESSAGE:
                    m = pb_value.add()
                    _dict_to_protobuf(m, item, type_callable_map, strict, ignore_none)
                elif field.type == FieldDescriptor.TYPE_ENUM and isinstance(item, six.string_types):
                    pb_value.append(_string_to_enum(field, item, strict))
                else:
                    pb_value.append(item)
            continue
        if isinstance(input_value, datetime.datetime):
            input_value = datetime_to_timestamp(input_value)
            # Instead of setattr we need to use CopyFrom for composite fields
            # Otherwise we will get AttributeError: Assignment not allowed to composite field "field name" in protocol message object
            getattr(pb, field.name).CopyFrom(input_value)
            continue
        elif field.type == FieldDescriptor.TYPE_MESSAGE:
            _dict_to_protobuf(pb_value, input_value, type_callable_map, strict, ignore_none)
            continue

        if field.type in type_callable_map:
            input_value = type_callable_map[field.type](input_value)

        if field.is_extension:
            pb.Extensions[field] = input_value
            continue

        if field.type == FieldDescriptor.TYPE_ENUM and isinstance(input_value, six.string_types):
            input_value = _string_to_enum(field, input_value, strict)

        setattr(pb, field.name, input_value)

    return pb