31 """Dynamic Protobuf class creator."""
33 from collections
import OrderedDict
43 """Get a proto class from the MessageFactory by name.
46 factory: a MessageFactory instance.
47 full_name: str, the fully qualified name of the proto type.
49 A class, for the type identified by full_name.
51 KeyError, if the proto is not found in the factory's descriptor pool.
53 proto_descriptor = factory.pool.FindMessageTypeByName(full_name)
54 proto_cls = factory.GetPrototype(proto_descriptor)
59 """Create a Protobuf class whose fields are basic types.
61 Note: this doesn't validate field names!
64 fields: dict of {name: field_type} mappings for each field in the proto. If
65 this is an OrderedDict the order will be maintained, otherwise the
66 fields will be sorted by name.
67 full_name: optional str, the fully-qualified name of the proto type.
68 pool: optional DescriptorPool instance.
70 a class, the new protobuf class with a FileDescriptor.
72 factory = message_factory.MessageFactory(pool=pool)
74 if full_name
is not None:
85 field_items = fields.items()
86 if not isinstance(fields, OrderedDict):
87 field_items = sorted(field_items)
91 fields_hash = hashlib.sha1()
92 for f_name, f_type
in field_items:
93 fields_hash.update(f_name.encode(
'utf-8'))
94 fields_hash.update(
str(f_type).
encode(
'utf-8'))
95 proto_file_name = fields_hash.hexdigest() +
'.proto'
99 full_name = (
'net.proto2.python.public.proto_builder.AnonymousProto_' +
100 fields_hash.hexdigest())
115 """Populate FileDescriptorProto for MessageFactory's DescriptorPool."""
116 package, name = full_name.rsplit(
'.', 1)
117 file_proto = descriptor_pb2.FileDescriptorProto()
118 file_proto.name = os.path.join(package.replace(
'.',
'/'), proto_file_name)
119 file_proto.package = package
120 desc_proto = file_proto.message_type.add()
121 desc_proto.name = name
122 for f_number, (f_name, f_type)
in enumerate(field_items, 1):
123 field_proto = desc_proto.field.add()
124 field_proto.name = f_name
127 if f_number >= descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER:
129 descriptor.FieldDescriptor.LAST_RESERVED_FIELD_NUMBER -
130 descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER + 1)
131 field_proto.number = f_number
132 field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
133 field_proto.type = f_type