當前位置: 首頁>>代碼示例>>Python>>正文


Python message.Message方法代碼示例

本文整理匯總了Python中google.protobuf.message.Message方法的典型用法代碼示例。如果您正苦於以下問題:Python message.Message方法的具體用法?Python message.Message怎麽用?Python message.Message使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在google.protobuf.message的用法示例。


在下文中一共展示了message.Message方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: environ

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def environ(self, *proto_msgs, **kwargs):
    """Sets environment data for this test case."""
    ret = self.test(None)

    to_apply = []

    for msg in proto_msgs:
      if not isinstance(msg, PBMessage):
        raise ValueError(
            'Positional arguments for api.properties must be protobuf messages.'
            ' Got: %r (type %r)' % (msg, type(msg)))
      to_apply.append(jsonpb.MessageToDict(
          msg, preserving_proto_field_name=True))

    to_apply.append(kwargs)

    for dictionary in to_apply:
      for key, value in dictionary.iteritems():
        if not isinstance(value, (int, float, basestring)):
          raise ValueError(
              'Environment values must be int, float or string. '
              'Got: %r=%r (type %r)' % (key, value, type(value)))
        ret.environ[key] = str(value)

    return ret 
開發者ID:luci,項目名稱:recipes-py,代碼行數:27,代碼來源:test_api.py

示例2: setdefault

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def setdefault(pb_or_dict, key, value):
    """Set the key on the object to the value if the current value is falsy.

    Because protobuf Messages do not distinguish between unset values and
    falsy ones particularly well, this method treats any falsy value
    (e.g. 0, empty list) as a target to be overwritten, on both Messages
    and dictionaries.

    Args:
        pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
            object.
        key (str): The key on the object in question.
        value (Any): The value to set.

    Raises:
        TypeError: If pb_or_dict is not a Message or Mapping.
    """
    if not get(pb_or_dict, key, default=None):
        set(pb_or_dict, key, value) 
開發者ID:googleapis,項目名稱:gax-python,代碼行數:21,代碼來源:protobuf.py

示例3: testParsingFlatClassWithExplicitClassDeclaration

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(message.Message, metaclass=reflection.GeneratedProtocolMessageType):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
開發者ID:katharosada,項目名稱:botchallenge,代碼行數:18,代碼來源:reflection_test.py

示例4: new_context

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def new_context(self, **section_pb_values):
    """Creates a new LUCI_CONTEXT file with the provided section values, all
    unmentioned sections in the current context will be copied over. The
    environment variable will NOT not be switched to the newly created context.

    Args:
      * section_pb_values (Dict[str, message.Message]) - A mapping of
        section_key to the new message value for that section.

    Returns the path (str) to the newly created LUCI_CONTEXT file. Returns None
    if section_pb_values is empty (i.e. No change to current context).
    """
    section_values = {
      key: jsonpb.MessageToDict(pb_val)
      for key, pb_val in iteritems(section_pb_values)
    }
    with luci_context.stage(_leak=True, **section_values) as file_path:
      return file_path 
開發者ID:luci,項目名稱:recipes-py,代碼行數:20,代碼來源:recipe_api.py

示例5: testParsingFlatClassWithExplicitClassDeclaration

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:25,代碼來源:reflection_test.py

示例6: _AddMessageMethods

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def _AddMessageMethods(message_descriptor, cls):
  """Adds implementations of all Message methods to cls."""
  _AddListFieldsMethod(message_descriptor, cls)
  _AddHasFieldMethod(message_descriptor, cls)
  _AddClearFieldMethod(message_descriptor, cls)
  if message_descriptor.is_extendable:
    _AddClearExtensionMethod(cls)
    _AddHasExtensionMethod(cls)
  _AddEqualsMethod(message_descriptor, cls)
  _AddStrMethod(message_descriptor, cls)
  _AddReprMethod(message_descriptor, cls)
  _AddUnicodeMethod(message_descriptor, cls)
  _AddByteSizeMethod(message_descriptor, cls)
  _AddSerializeToStringMethod(message_descriptor, cls)
  _AddSerializePartialToStringMethod(message_descriptor, cls)
  _AddMergeFromStringMethod(message_descriptor, cls)
  _AddIsInitializedMethod(message_descriptor, cls)
  _AddMergeFromMethod(cls)
  _AddWhichOneofMethod(message_descriptor, cls)
  _AddReduceMethod(cls)
  # Adds methods which do not depend on cls.
  cls.Clear = _Clear
  cls.DiscardUnknownFields = _DiscardUnknownFields
  cls._SetListener = _SetListener 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:26,代碼來源:python_message.py

示例7: _AddMessageMethods

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def _AddMessageMethods(message_descriptor, cls):
  """Adds implementations of all Message methods to cls."""
  _AddListFieldsMethod(message_descriptor, cls)
  _AddHasFieldMethod(message_descriptor, cls)
  _AddClearFieldMethod(message_descriptor, cls)
  if message_descriptor.is_extendable:
    _AddClearExtensionMethod(cls)
    _AddHasExtensionMethod(cls)
  _AddEqualsMethod(message_descriptor, cls)
  _AddStrMethod(message_descriptor, cls)
  _AddReprMethod(message_descriptor, cls)
  _AddUnicodeMethod(message_descriptor, cls)
  _AddByteSizeMethod(message_descriptor, cls)
  _AddSerializeToStringMethod(message_descriptor, cls)
  _AddSerializePartialToStringMethod(message_descriptor, cls)
  _AddMergeFromStringMethod(message_descriptor, cls)
  _AddIsInitializedMethod(message_descriptor, cls)
  _AddMergeFromMethod(cls)
  _AddWhichOneofMethod(message_descriptor, cls)
  # Adds methods which do not depend on cls.
  cls.Clear = _Clear
  cls.DiscardUnknownFields = _DiscardUnknownFields
  cls._SetListener = _SetListener 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:25,代碼來源:python_message.py

示例8: get_messages

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def get_messages(module):
    """Return a dictionary of message names and objects.

    Args:
        module (module): A Python module; dir() will be run against this
            module to find Message subclasses.

    Returns:
        dict[str, Message]: A dictionary with the Message class names as
            keys, and the Message subclasses themselves as values.
    """
    answer = collections.OrderedDict()
    for name in dir(module):
        candidate = getattr(module, name)
        if inspect.isclass(candidate) and issubclass(candidate, Message):
            answer[name] = candidate
    return answer 
開發者ID:googleapis,項目名稱:gax-python,代碼行數:19,代碼來源:messages.py

示例9: _AddMessageMethods

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def _AddMessageMethods(message_descriptor, cls):
  """Adds implementations of all Message methods to cls."""
  _AddListFieldsMethod(message_descriptor, cls)
  _AddHasFieldMethod(message_descriptor, cls)
  _AddClearFieldMethod(message_descriptor, cls)
  if message_descriptor.is_extendable:
    _AddClearExtensionMethod(cls)
    _AddHasExtensionMethod(cls)
  _AddClearMethod(message_descriptor, cls)
  _AddEqualsMethod(message_descriptor, cls)
  _AddStrMethod(message_descriptor, cls)
  _AddUnicodeMethod(message_descriptor, cls)
  _AddSetListenerMethod(cls)
  _AddByteSizeMethod(message_descriptor, cls)
  _AddSerializeToStringMethod(message_descriptor, cls)
  _AddSerializePartialToStringMethod(message_descriptor, cls)
  _AddMergeFromStringMethod(message_descriptor, cls)
  _AddIsInitializedMethod(message_descriptor, cls)
  _AddMergeFromMethod(cls)
  _AddWhichOneofMethod(message_descriptor, cls) 
開發者ID:sklearn-theano,項目名稱:sklearn-theano,代碼行數:22,代碼來源:python_message.py

示例10: proto_to_dict

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def proto_to_dict(message):
    """Converts protobuf message instance to dict

    :param message: protobuf message instance
    :return: parameters and their values
    :rtype: dict
    :raises: :class:`.TypeError` if ``message`` is not a proto message
    """
    if not isinstance(message, _ProtoMessageType):
        raise TypeError("Expected `message` to be a instance of protobuf message")

    data = {}

    for desc, field in message.ListFields():
        if desc.type == desc.TYPE_MESSAGE:
            if desc.label == desc.LABEL_REPEATED:
                data[desc.name] = list(map(proto_to_dict, field))
            else:
                data[desc.name] = proto_to_dict(field)
        else:
            data[desc.name] = list(field) if desc.label == desc.LABEL_REPEATED else field

    return data 
開發者ID:ValvePython,項目名稱:steam,代碼行數:25,代碼來源:proto.py

示例11: dict_to_protobuf

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def dict_to_protobuf(pb_klass_or_instance, values, type_callable_map=REVERSE_TYPE_CALLABLE_MAP, \
    strict=True):
    """Populates a protobuf model from a dictionary.

    :param pb_klass_or_instance: a protobuf message class, or an protobuf instance
    :type pb_klass_or_instance: a type or instance of a subclass of google.protobuf.message.Message
    :param dict values: a dictionary of values. Repeated and nested values are
       fully supported.
    :param dict type_callable_map: a mapping of protobuf types to callables for setting
       values on the target instance.
    :param bool strict: complain if keys in the map are not fields on the message.
    """
    if isinstance(pb_klass_or_instance, Message):
        instance = pb_klass_or_instance
    else:
        instance = pb_klass_or_instance()
    return _dict_to_protobuf(instance, values, type_callable_map, strict) 
開發者ID:advboxes,項目名稱:perceptron-benchmark,代碼行數:19,代碼來源:protobuf_to_dict.py

示例12: __init__

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def __init__(cls, name, bases, dictionary):
    """Here we perform the majority of our work on the class.
    We add enum getters, an __init__ method, implementations
    of all Message methods, and properties for all fields
    in the protocol type.

    Args:
      name: Name of the class (ignored, but required by the
        metaclass protocol).
      bases: Base classes of the class we're constructing.
        (Should be message.Message).  We ignore this field, but
        it's required by the metaclass protocol
      dictionary: The class dictionary of the class we're
        constructing.  dictionary[_DESCRIPTOR_KEY] must contain
        a Descriptor object describing this protocol message
        type.
    """
    descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
    _InitMessage(descriptor, cls)
    superclass = super(GeneratedProtocolMessageType, cls)
    superclass.__init__(name, bases, dictionary) 
開發者ID:katharosada,項目名稱:botchallenge,代碼行數:23,代碼來源:reflection.py

示例13: luci_context

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def luci_context(self, **section_pb_values):
    """Sets the LUCI_CONTEXT for this test case.

    Args:
      * section_pb_values(Dict[str, message.Message]): A mapping of section_key
      to the proto value for that section.
    """
    ret = self.test(None)
    for section_key, pb_val in iteritems(section_pb_values):
      if not isinstance(pb_val, message.Message): # pragma: no cover
          raise ValueError(
              'Expected section value in LUCI_CONTEXT to be proto message;'
              'Got: %r=%r (type %r)' % (section_key, pb_val, type(pb_val)))
      ret.luci_context[section_key] = jsonpb.MessageToDict(pb_val)
    return ret 
開發者ID:luci,項目名稱:recipes-py,代碼行數:17,代碼來源:test_api.py

示例14: __call__

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def __call__(self, *proto_msgs, **kwargs):
    """Sets property data for this test case.

    You may pass a list of protobuf messages to use; their JSONPB
    representations will be merged together with `dict.update`.

    You may also pass explicit key/value pairs; these will be merged into
    properties at the top level with `dict.update`.
    """
    ret = self.test(None)

    for msg in proto_msgs:
      if not isinstance(msg, PBMessage):
        raise ValueError(
            'Positional arguments for api.properties must be protobuf messages.'
            ' Got: %r (type %r)' % (msg, type(msg)))
      ret.properties.update(**jsonpb.MessageToDict(
          msg, preserving_proto_field_name=True))

    for key, value in kwargs.iteritems():
      if isinstance(value, PBMessage):
        value = jsonpb.MessageToDict(value, preserving_proto_field_name=True)
      # TODO(iannucci): recursively validate type of value to be all JSONish
      # types.
      # TODO(iannucci): recursively convert Path instances to string here.
      ret.properties[key] = value

    return ret 
開發者ID:luci,項目名稱:recipes-py,代碼行數:30,代碼來源:test_api.py

示例15: output

# 需要導入模塊: from google.protobuf import message [as 別名]
# 或者: from google.protobuf.message import Message [as 別名]
def output(proto_msg, retcode=None, name=None):
    """Supplies placeholder data for a proto.output.

    Args:
      * proto_msg - Instance of a proto message that should be returned for this
        placeholder.
      * retcode (Optional[int]) - The returncode of the step.
      * name (Optional[str]) - The name of the placeholder you're mocking.
    """
    if not isinstance(proto_msg, message.Message): # pragma: no cover
      raise ValueError("expected proto Message, got: %r" % (type(proto_msg),))
    return proto_msg, retcode, name 
開發者ID:luci,項目名稱:recipes-py,代碼行數:14,代碼來源:test_api.py


注:本文中的google.protobuf.message.Message方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。