本文整理汇总了Python中google.protobuf.any_pb2.Any方法的典型用法代码示例。如果您正苦于以下问题:Python any_pb2.Any方法的具体用法?Python any_pb2.Any怎么用?Python any_pb2.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.protobuf.any_pb2
的用法示例。
在下文中一共展示了any_pb2.Any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testPackWithCustomTypeUrl
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def testPackWithCustomTypeUrl(self):
submessage = any_test_pb2.TestAny()
submessage.int_value = 12345
msg = any_pb2.Any()
# Pack with a custom type URL prefix.
msg.Pack(submessage, 'type.myservice.com')
self.assertEqual(msg.type_url,
'type.myservice.com/%s' % submessage.DESCRIPTOR.full_name)
# Pack with a custom type URL prefix ending with '/'.
msg.Pack(submessage, 'type.myservice.com/')
self.assertEqual(msg.type_url,
'type.myservice.com/%s' % submessage.DESCRIPTOR.full_name)
# Pack with an empty type URL prefix.
msg.Pack(submessage, '')
self.assertEqual(msg.type_url,
'/%s' % submessage.DESCRIPTOR.full_name)
# Test unpacking the type.
unpacked_message = any_test_pb2.TestAny()
self.assertTrue(msg.Unpack(unpacked_message))
self.assertEqual(submessage, unpacked_message)
示例2: testInvalidAny
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def testInvalidAny(self):
message = any_pb2.Any()
text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
self.assertRaisesRegex(
KeyError,
'value',
json_format.Parse, text, message)
text = '{"value": 1234}'
self.assertRaisesRegex(
json_format.ParseError,
'@type is missing when parsing any message.',
json_format.Parse, text, message)
text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
self.assertRaisesRegex(
TypeError,
'Can not find message descriptor by type_url: '
'type.googleapis.com/MessageNotExist.',
json_format.Parse, text, message)
# Only last part is to be used: b/25630112
text = (r'{"@type": "incorrect.googleapis.com/google.protobuf.Int32Value",'
r'"value": 1234}')
json_format.Parse(text, message)
示例3: _get_kind_name
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def _get_kind_name(item):
"""Returns the kind name in CollectionDef.
Args:
item: A data item.
Returns:
The string representation of the kind in CollectionDef.
"""
if isinstance(item, (six.string_types, six.binary_type)):
kind = "bytes_list"
elif isinstance(item, six.integer_types):
kind = "int64_list"
elif isinstance(item, float):
kind = "float_list"
elif isinstance(item, Any):
kind = "any_list"
else:
kind = "node_list"
return kind
示例4: testInvalidAny
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def testInvalidAny(self):
message = any_pb2.Any()
text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
self.assertRaisesRegexp(
KeyError,
'value',
json_format.Parse, text, message)
text = '{"value": 1234}'
self.assertRaisesRegexp(
json_format.ParseError,
'@type is missing when parsing any message.',
json_format.Parse, text, message)
text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
self.assertRaisesRegexp(
TypeError,
'Can not find message descriptor by type_url: '
'type.googleapis.com/MessageNotExist.',
json_format.Parse, text, message)
# Only last part is to be used: b/25630112
text = (r'{"@type": "incorrect.googleapis.com/google.protobuf.Int32Value",'
r'"value": 1234}')
json_format.Parse(text, message)
示例5: _pack_values
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def _pack_values(values):
"""Pack protobuf values."""
packed = {}
if values is None:
return packed
for key, value in six.iteritems(values):
packed_value = Any()
if isinstance(value, float):
packed_value.Pack(wrappers_pb2.DoubleValue(value=value))
elif isinstance(value, six.integer_types):
packed_value.Pack(wrappers_pb2.Int64Value(value=value))
elif isinstance(value, six.string_types):
packed_value.Pack(wrappers_pb2.StringValue(value=value))
else:
raise ValueError('Unknown stat type for ' + key)
packed[key] = packed_value
return packed
示例6: pack_graph_def
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def pack_graph_def(graph_def):
"""Pack a `tf.compat.v1.GraphDef` into a proto3 `Any` message.
Args:
graph_def: the `tf.compat.v1.GraphDef` to pack into a protocol buffer
message.
Returns:
A `google.protobuf.Any` protocol buffer message.
Raises:
TypeError: if `graph_def` is not a `tf.compat.v1.GraphDef`.
"""
py_typecheck.check_type(graph_def, tf.compat.v1.GraphDef)
_check_no_graph_level_seed(graph_def)
any_pb = any_pb2.Any()
any_pb.Pack(graph_def)
return any_pb
示例7: unpack_graph_def
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def unpack_graph_def(any_pb):
"""Unpacks a proto3 `Any` message to a `tf.compat.v1.GraphDef`.
Args:
any_pb: the `Any` message to unpack.
Returns:
A `tf.compat.v1.GraphDef`.
Raises:
ValueError: if the object packed into `any_pb` cannot be unpacked as
`tf.compat.v1.GraphDef`.
TypeError: if `any_pb` is not an `Any` protocol buffer message.
"""
py_typecheck.check_type(any_pb, any_pb2.Any)
graph_def = tf.compat.v1.GraphDef()
if not any_pb.Unpack(graph_def):
raise ValueError(
'Unable to unpack value [{}] as a tf.compat.v1.GraphDef'.format(any_pb))
return graph_def
示例8: test_compute_returns_result
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def test_compute_returns_result(self, mock_stub):
tensor_proto = tf.make_tensor_proto(1)
any_pb = any_pb2.Any()
any_pb.Pack(tensor_proto)
value = executor_pb2.Value(tensor=any_pb)
response = executor_pb2.ComputeResponse(value=value)
instance = mock_stub.return_value
instance.Compute = mock.Mock(side_effect=[response])
loop = asyncio.get_event_loop()
executor = create_remote_executor()
type_signature = computation_types.FunctionType(None, tf.int32)
comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,
executor)
result = loop.run_until_complete(comp.compute())
instance.Compute.assert_called_once()
self.assertEqual(result, 1)
示例9: get_node_wrapped_tensor_info
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def get_node_wrapped_tensor_info(meta_graph_def: meta_graph_pb2.MetaGraphDef,
path: Text) -> any_pb2.Any:
"""Get the Any-wrapped TensorInfo for the node from the meta_graph_def.
Args:
meta_graph_def: MetaGraphDef containing the CollectionDefs to extract the
node name from.
path: Name of the collection containing the node name.
Returns:
The Any-wrapped TensorInfo for the node retrieved from the CollectionDef.
Raises:
KeyError: There was no CollectionDef with the given name (path).
ValueError: The any_list in the CollectionDef with the given name did
not have length 1.
"""
if path not in meta_graph_def.collection_def:
raise KeyError('could not find path %s in collection defs. meta_graph_def '
'was %s' % (path, meta_graph_def))
if len(meta_graph_def.collection_def[path].any_list.value) != 1:
raise ValueError(
'any_list should be of length 1. path was %s, any_list was: %s.' %
(path, meta_graph_def.collection_def[path].any_list.value))
return meta_graph_def.collection_def[path].any_list.value[0]
示例10: encode_tensor_node
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def encode_tensor_node(node: types.TensorType) -> any_pb2.Any:
"""Encode a "reference" to a Tensor/SparseTensor as a TensorInfo in an Any.
We put the Tensor / SparseTensor in a TensorInfo, which we then wrap in an
Any so that it can be added to the CollectionDef.
Args:
node: Tensor node.
Returns:
Any proto wrapping a TensorInfo.
"""
any_buf = any_pb2.Any()
tensor_info = tf.compat.v1.saved_model.utils.build_tensor_info(node)
any_buf.Pack(tensor_info)
return any_buf
示例11: decode_tensor_node
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def decode_tensor_node(graph: tf.Graph,
encoded_tensor_node: any_pb2.Any) -> types.TensorType:
"""Decode an encoded Tensor node encoded with encode_tensor_node.
Decodes the encoded Tensor "reference", and returns the node in the given
graph corresponding to that Tensor.
Args:
graph: Graph the Tensor
encoded_tensor_node: Encoded Tensor.
Returns:
Decoded Tensor.
"""
tensor_info = meta_graph_pb2.TensorInfo()
encoded_tensor_node.Unpack(tensor_info)
return tf.compat.v1.saved_model.utils.get_tensor_from_tensor_info(
tensor_info, graph)
示例12: OnInvoke
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def OnInvoke(self, request, context):
data = None
content_type = ""
logger.info("================== REQUEST ==================")
logger.info(f"Content Type: {request.content_type}")
logger.info(f"Message: {request.data.value}")
if request.method == 'my_method':
data = Any(value='SMSG_INVOKE_REQUEST'.encode('utf-8'))
content_type = "text/plain; charset=UTF-8"
else:
data = Any(value='METHOD_NOT_SUPPORTED'.encode('utf-8'))
content_type = "text/plain; charset=UTF-8"
return commonv1pb.InvokeResponse(data=data, content_type=content_type)
# Create a gRPC server
示例13: OnInvoke
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def OnInvoke(self, request, context):
data=None
content_type=""
if request.method == 'my_method':
custom_response = response_messages.CustomResponse(isSuccess=True, code=200, message="Hello World - Success!")
data = Any()
data.Pack(custom_response)
else:
data = Any(value='METHOD_NOT_SUPPORTED'.encode('utf-8'))
content_type="text/plain"
print(data, flush=True)
print(content_type, flush=True)
return common_v1.InvokeResponse(data=data, content_type=content_type)
# Create a gRPC server
示例14: testSnakeCaseToCamelCase
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def testSnakeCaseToCamelCase(self):
self.assertEqual('fooBar',
well_known_types._SnakeCaseToCamelCase('foo_bar'))
self.assertEqual('FooBar',
well_known_types._SnakeCaseToCamelCase('_foo_bar'))
self.assertEqual('foo3Bar',
well_known_types._SnakeCaseToCamelCase('foo3_bar'))
# No uppercase letter is allowed.
self.assertRaisesRegex(
well_known_types.Error,
'Fail to print FieldMask to Json string: Path name Foo must '
'not contain uppercase letters.',
well_known_types._SnakeCaseToCamelCase,
'Foo')
# Any character after a "_" must be a lowercase letter.
# 1. "_" cannot be followed by another "_".
# 2. "_" cannot be followed by a digit.
# 3. "_" cannot appear as the last character.
self.assertRaisesRegex(
well_known_types.Error,
'Fail to print FieldMask to Json string: The character after a '
'"_" must be a lowercase letter in path name foo__bar.',
well_known_types._SnakeCaseToCamelCase,
'foo__bar')
self.assertRaisesRegex(
well_known_types.Error,
'Fail to print FieldMask to Json string: The character after a '
'"_" must be a lowercase letter in path name foo_3bar.',
well_known_types._SnakeCaseToCamelCase,
'foo_3bar')
self.assertRaisesRegex(
well_known_types.Error,
'Fail to print FieldMask to Json string: Trailing "_" in path '
'name foo_bar_.',
well_known_types._SnakeCaseToCamelCase,
'foo_bar_')
示例15: testAnyMessage
# 需要导入模块: from google.protobuf import any_pb2 [as 别名]
# 或者: from google.protobuf.any_pb2 import Any [as 别名]
def testAnyMessage(self):
# Creates and sets message.
msg = any_test_pb2.TestAny()
msg_descriptor = msg.DESCRIPTOR
all_types = unittest_pb2.TestAllTypes()
all_descriptor = all_types.DESCRIPTOR
all_types.repeated_string.append('\u00fc\ua71f')
# Packs to Any.
msg.value.Pack(all_types)
self.assertEqual(msg.value.type_url,
'type.googleapis.com/%s' % all_descriptor.full_name)
self.assertEqual(msg.value.value,
all_types.SerializeToString())
# Tests Is() method.
self.assertTrue(msg.value.Is(all_descriptor))
self.assertFalse(msg.value.Is(msg_descriptor))
# Unpacks Any.
unpacked_message = unittest_pb2.TestAllTypes()
self.assertTrue(msg.value.Unpack(unpacked_message))
self.assertEqual(all_types, unpacked_message)
# Unpacks to different type.
self.assertFalse(msg.value.Unpack(msg))
# Only Any messages have Pack method.
try:
msg.Pack(all_types)
except AttributeError:
pass
else:
raise AttributeError('%s should not have Pack method.' %
msg_descriptor.full_name)