31 """Dynamic Protobuf class creator."""
34 from collections
import OrderedDict
36 from ordereddict
import OrderedDict
45 """Get a proto class from the MessageFactory by name.
48 factory: a MessageFactory instance.
49 full_name: str, the fully qualified name of the proto type.
51 A class, for the type identified by full_name.
53 KeyError, if the proto is not found in the factory's descriptor pool.
55 proto_descriptor = factory.pool.FindMessageTypeByName(full_name)
56 proto_cls = factory.GetPrototype(proto_descriptor)
61 """Create a Protobuf class whose fields are basic types.
63 Note: this doesn't validate field names!
66 fields: dict of {name: field_type} mappings for each field in the proto. If
67 this is an OrderedDict the order will be maintained, otherwise the
68 fields will be sorted by name.
69 full_name: optional str, the fully-qualified name of the proto type.
70 pool: optional DescriptorPool instance.
72 a class, the new protobuf class with a FileDescriptor.
76 if full_name
is not None:
87 field_items = fields.items()
88 if not isinstance(fields, OrderedDict):
89 field_items = sorted(field_items)
93 fields_hash = hashlib.sha1()
94 for f_name, f_type
in field_items:
95 fields_hash.update(f_name.encode(
'utf-8'))
96 fields_hash.update(
str(f_type).encode(
'utf-8'))
97 proto_file_name = fields_hash.hexdigest() +
'.proto'
100 if full_name
is None:
101 full_name = (
'net.proto2.python.public.proto_builder.AnonymousProto_' +
102 fields_hash.hexdigest())
117 """Populate FileDescriptorProto for MessageFactory's DescriptorPool."""
118 package, name = full_name.rsplit(
'.', 1)
119 file_proto = descriptor_pb2.FileDescriptorProto()
120 file_proto.name = os.path.join(package.replace(
'.',
'/'), proto_file_name)
121 file_proto.package = package
122 desc_proto = file_proto.message_type.add()
123 desc_proto.name = name
124 for f_number, (f_name, f_type)
in enumerate(field_items, 1):
125 field_proto = desc_proto.field.add()
126 field_proto.name = f_name
127 field_proto.number = f_number
128 field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
129 field_proto.type = f_type