本文整理汇总了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
示例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)
示例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])
示例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
示例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])
示例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
示例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
示例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
示例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)
示例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
示例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)
示例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)
示例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
示例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
示例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