本文整理汇总了Python中google.protobuf.json_format.MessageToDict方法的典型用法代码示例。如果您正苦于以下问题:Python json_format.MessageToDict方法的具体用法?Python json_format.MessageToDict怎么用?Python json_format.MessageToDict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.protobuf.json_format
的用法示例。
在下文中一共展示了json_format.MessageToDict方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: environ
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [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: _transform
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def _transform(pb_node):
fields = []
for i in pb_node.items:
item_type = i.WhichOneof('value')
if item_type == 'field':
if not i.field.name:
raise TypeError('Field name is empty: {!r}'.format(i))
options = None
if i.field.HasField('options'):
options = MessageToDict(i.field.options)
fields.append(Field(i.field.name, options))
elif item_type == 'link':
if not i.link.name:
raise TypeError('Link name is empty: {!r}'.format(i))
options = None
if i.link.HasField('options'):
options = MessageToDict(i.link.options)
fields.append(Link(i.link.name, _transform(i.link.node), options))
else:
raise TypeError('Node item is empty: {!r}'.format(i))
return Node(fields)
示例3: GenTests
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def GenTests(api):
yield (
api.test('basic') +
api.buildbucket.simulated_get(build_pb2.Build(
id=9016911228971028736, status=common_pb2.SUCCESS,
)) +
api.buildbucket.simulated_get_multi([
build_pb2.Build(id=9016911228971028736, status=common_pb2.SUCCESS),
build_pb2.Build(id=9016911228971028737, status=common_pb2.SUCCESS),
]) +
api.buildbucket.simulated_buildbucket_output(None, step_name='legacy_get')
)
yield (
api.test('failed request') +
api.step_data(
'buildbucket.get',
api.json.output_stream(
json_format.MessageToDict(builds_service_pb2.BatchResponse(
responses=[dict(error=dict(message='there was a problem'))],
)),
),
)
)
示例4: __call__
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def __call__(self, hostname=None, triggers=None):
"""Emulates scheduler module state.
triggers must be None or a list of triggers_pb2.Trigger objects.
"""
assert hostname is None or isinstance(hostname, basestring)
assert not triggers or all(
isinstance(t, triggers_pb2.Trigger) for t in triggers)
ret = self.test(None)
ret.properties.update(**{
'$recipe_engine/scheduler': {
'hostname': hostname,
'triggers': [json_format.MessageToDict(t) for t in triggers or []],
},
})
return ret
示例5: test_rolls
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def test_rolls(recipe_deps, verbose_json):
candidates, rejected_candidates, repos = get_roll_candidates(recipe_deps)
roll_details = []
picked_roll_details = None
trivial = True
if candidates:
trivial, picked_roll_details, roll_details = process_candidates(
recipe_deps, candidates, repos, verbose_json)
ret = {
# it counts as success if there are no candidates at all :)
'success': bool(not candidates or picked_roll_details),
'trivial': trivial,
'roll_details': roll_details,
'picked_roll_details': picked_roll_details,
'rejected_candidates_count': len(rejected_candidates),
}
if verbose_json:
ret['rejected_candidate_specs'] = [
jsonpb.MessageToDict(c.repo_spec, preserving_proto_field_name=True)
for c in rejected_candidates
]
return ret
示例6: testExtensionSerializationDictMatchesProto3Spec
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def testExtensionSerializationDictMatchesProto3Spec(self):
"""See go/proto3-json-spec for spec.
"""
message = unittest_mset_pb2.TestMessageSetContainer()
ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
message.message_set.Extensions[ext1].i = 23
message.message_set.Extensions[ext2].str = 'foo'
message_dict = json_format.MessageToDict(
message
)
golden_dict = {
'messageSet': {
'[protobuf_unittest.'
'TestMessageSetExtension1.messageSetExtension]': {
'i': 23,
},
'[protobuf_unittest.'
'TestMessageSetExtension2.messageSetExtension]': {
'str': 'foo',
},
},
}
self.assertEqual(golden_dict, message_dict)
示例7: test_update_product_no_explicit_name
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def test_update_product_no_explicit_name(self, get_conn):
# Given
product = Product()
update_product_method = get_conn.return_value.update_product
update_product_method.return_value = product
product_name = ProductSearchClient.product_path(PROJECT_ID_TEST, LOC_ID_TEST, PRODUCT_ID_TEST)
# When
result = self.hook.update_product(
location=LOC_ID_TEST,
product_id=PRODUCT_ID_TEST,
product=product,
update_mask=None,
project_id=PROJECT_ID_TEST,
retry=None,
timeout=None,
metadata=None,
)
# Then
self.assertEqual(result, MessageToDict(product))
update_product_method.assert_called_once_with(
product=Product(name=product_name), metadata=None, retry=None, timeout=None, update_mask=None
)
示例8: execute
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def execute(self, context):
hook = CloudAutoMLHook(gcp_conn_id=self.gcp_conn_id)
self.log.info("Creating model.")
operation = hook.create_model(
model=self.model,
location=self.location,
project_id=self.project_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
result = MessageToDict(operation.result())
model_id = hook.extract_object_id(result)
self.log.info("Model created: %s", model_id)
self.xcom_push(context, key="model_id", value=model_id)
return result
示例9: execute
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def execute(self, context):
hook = CloudDLPHook(gcp_conn_id=self.gcp_conn_id)
try:
template = hook.create_deidentify_template(
organization_id=self.organization_id,
project_id=self.project_id,
deidentify_template=self.deidentify_template,
template_id=self.template_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
except AlreadyExists:
template = hook.get_deidentify_template(
organization_id=self.organization_id,
project_id=self.project_id,
template_id=self.template_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
return MessageToDict(template)
示例10: simulated_search_results
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def simulated_search_results(self, builds, step_name=None):
"""Simulates a buildbucket.search call."""
assert isinstance(builds, list), builds
assert all(isinstance(b, build_pb2.Build) for b in builds), builds
step_name = step_name or 'buildbucket.search'
lines = [json.dumps(json_format.MessageToDict(b)) for b in builds]
output = "\n".join(lines)
return self.step_data(step_name, self.m.raw_io.stream_output(output))
示例11: simulated_get
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def simulated_get(self, build, step_name=None):
"""Simulates a buildbucket.get call."""
step_name = step_name or 'buildbucket.get'
jsonish = json_format.MessageToDict(builds_service_pb2.BatchResponse(
responses=[dict(get_build=build)],
))
return self.step_data(step_name, self.m.json.output_stream(jsonish))
示例12: simulated_get_multi
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def simulated_get_multi(self, builds, step_name=None):
"""Simulates a buildbucket.get_multi call."""
step_name = step_name or 'buildbucket.get_multi'
jsonish = json_format.MessageToDict(builds_service_pb2.BatchResponse(
responses=[dict(get_build=b) for b in builds],
))
return self.step_data(step_name, self.m.json.output_stream(jsonish))
示例13: _simulated_batch_response
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def _simulated_batch_response(self, batch_response, step_name):
"""Simulate that the given step will write the provided batch response into
step data. The return code will be 1 for step data if the responses contain
error. Otherwise, 0
"""
assert isinstance(batch_response, builds_service_pb2.BatchResponse)
ret_code = int(any(r.HasField('error') for r in batch_response.responses))
jsonish = json_format.MessageToDict(batch_response)
return self.step_data(
step_name, self.m.json.output_stream(jsonish, retcode=ret_code))
示例14: luci_context
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [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
示例15: serialize
# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import MessageToDict [as 别名]
def serialize(inv_bundle, pretty=False):
"""Serializes invocations to a string.
The format corresponds to the format used by rdb-ls, unless pretty is True.
Args:
inv_bundle: dict {inv_id: Invocation}.
pretty: if True, returns a better-looking output, but not supported by
deserialize().
"""
lines = []
def add_line(inv_id, key, msg):
jsonish = {
'invocationId': inv_id,
key: json_format.MessageToDict(msg),
}
lines.append(
json.dumps(jsonish, sort_keys=True, indent=2 if pretty else None)
)
for inv_id, inv in inv_bundle.iteritems():
assert isinstance(inv, Invocation), inv
if inv.proto.ListFields(): # if something is set
add_line(inv_id, 'invocation', inv.proto)
for attr_name, typ, key in Invocation._COLLECTIONS:
for msg in getattr(inv, attr_name):
assert isinstance(msg, typ), msg
add_line(inv_id, key, msg)
return '\n'.join(lines)