我理解你是否想把 python 的 dict 直接转成 pb2.py 文件中的具体的信息类?然后自动填充对应的字段?希望对你有帮助
import simplejson
from google.protobuf.descriptor import FieldDescriptor as FD
class ConvertException(Exception):
pass
def dict2pb(cls, adict, strict=False):
obj = cls()
for field in obj.DESCRIPTOR.fields:
if not field.label == field.LABEL_REQUIRED:
continue
if not field.has_default_value:
continue
if not field.name in adict:
raise ConvertException('Field "%s" missing from descriptor dictionary.'
% field.name)
field_names = set([field.name for field in obj.DESCRIPTOR.fields])
if strict:
for key in adict.keys():
if key not in field_names:
raise ConvertException(
'Key "%s" can not be mapped to field in %s class.'
% (key, type(obj)))
for field in obj.DESCRIPTOR.fields:
if not field.name in adict:
continue
msg_type = field.message_type
if field.label == FD.LABEL_REPEATED:
if field.type == FD.TYPE_MESSAGE:
for sub_dict in adict[field.name]:
item = getattr(obj, field.name).add()
item.CopyFrom(dict2pb(msg_type._concrete_class, sub_dict))
else:
map(getattr(obj, field.name).append, adict[field.name])
else:
if field.type == FD.TYPE_MESSAGE:
value = dict2pb(msg_type._concrete_class, adict[field.name])
getattr(obj, field.name).CopyFrom(value)
else:
setattr(obj, field.name, adict[field.name])
return obj
身体最重要,找到一个人陪你走一辈子更不容易,可以跟女朋友商量下,回家乡看看机会,现在需要你承担起相应的责任呢
简历直接发邮箱吗.抽烟有啥福利啊