message_factory.py
Go to the documentation of this file.
1 # Protocol Buffers - Google's data interchange format
2 # Copyright 2008 Google Inc. All rights reserved.
3 # https://developers.google.com/protocol-buffers/
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
7 # met:
8 #
9 # * Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # * Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following disclaimer
13 # in the documentation and/or other materials provided with the
14 # distribution.
15 # * Neither the name of Google Inc. nor the names of its
16 # contributors may be used to endorse or promote products derived from
17 # this software without specific prior written permission.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 """Provides a factory class for generating dynamic messages.
32 
33 The easiest way to use this class is if you have access to the FileDescriptor
34 protos containing the messages you want to create you can just do the following:
35 
36 message_classes = message_factory.GetMessages(iterable_of_file_descriptors)
37 my_proto_instance = message_classes['some.proto.package.MessageName']()
38 """
39 
40 __author__ = 'matthewtoia@google.com (Matt Toia)'
41 
42 from google.protobuf.internal import api_implementation
43 from google.protobuf import descriptor_pool
44 from google.protobuf import message
45 
46 if api_implementation.Type() == 'cpp':
47  from google.protobuf.pyext import cpp_message as message_impl
48 else:
49  from google.protobuf.internal import python_message as message_impl
50 
51 
52 # The type of all Message classes.
53 _GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType
54 
55 
56 class MessageFactory(object):
57  """Factory for creating Proto2 messages from descriptors in a pool."""
58 
59  def __init__(self, pool=None):
60  """Initializes a new factory."""
62 
63  # local cache of all classes built from protobuf descriptors
64  self._classes = {}
65 
66  def GetPrototype(self, descriptor):
67  """Builds a proto2 message class based on the passed in descriptor.
68 
69  Passing a descriptor with a fully qualified name matching a previous
70  invocation will cause the same class to be returned.
71 
72  Args:
73  descriptor: The descriptor to build from.
74 
75  Returns:
76  A class describing the passed in descriptor.
77  """
78  if descriptor not in self._classes:
79  descriptor_name = descriptor.name
80  if str is bytes: # PY2
81  descriptor_name = descriptor.name.encode('ascii', 'ignore')
82  result_class = _GENERATED_PROTOCOL_MESSAGE_TYPE(
83  descriptor_name,
84  (message.Message,),
85  {'DESCRIPTOR': descriptor, '__module__': None})
86  # If module not set, it wrongly points to message_factory module.
87  self._classes[descriptor] = result_class
88  for field in descriptor.fields:
89  if field.message_type:
90  self.GetPrototype(field.message_type)
91  for extension in result_class.DESCRIPTOR.extensions:
92  if extension.containing_type not in self._classes:
93  self.GetPrototype(extension.containing_type)
94  extended_class = self._classes[extension.containing_type]
95  extended_class.RegisterExtension(extension)
96  return self._classes[descriptor]
97 
98  def GetMessages(self, files):
99  """Gets all the messages from a specified file.
100 
101  This will find and resolve dependencies, failing if the descriptor
102  pool cannot satisfy them.
103 
104  Args:
105  files: The file names to extract messages from.
106 
107  Returns:
108  A dictionary mapping proto names to the message classes. This will include
109  any dependent messages as well as any messages defined in the same file as
110  a specified message.
111  """
112  result = {}
113  for file_name in files:
114  file_desc = self.pool.FindFileByName(file_name)
115  for desc in file_desc.message_types_by_name.values():
116  result[desc.full_name] = self.GetPrototype(desc)
117 
118  # While the extension FieldDescriptors are created by the descriptor pool,
119  # the python classes created in the factory need them to be registered
120  # explicitly, which is done below.
121  #
122  # The call to RegisterExtension will specifically check if the
123  # extension was already registered on the object and either
124  # ignore the registration if the original was the same, or raise
125  # an error if they were different.
126 
127  for extension in file_desc.extensions_by_name.values():
128  if extension.containing_type not in self._classes:
129  self.GetPrototype(extension.containing_type)
130  extended_class = self._classes[extension.containing_type]
131  extended_class.RegisterExtension(extension)
132  return result
133 
134 
135 _FACTORY = MessageFactory()
136 
137 
138 def GetMessages(file_protos):
139  """Builds a dictionary of all the messages available in a set of files.
140 
141  Args:
142  file_protos: Iterable of FileDescriptorProto to build messages out of.
143 
144  Returns:
145  A dictionary mapping proto names to the message classes. This will include
146  any dependent messages as well as any messages defined in the same file as
147  a specified message.
148  """
149  # The cpp implementation of the protocol buffer library requires to add the
150  # message in topological order of the dependency graph.
151  file_by_name = {file_proto.name: file_proto for file_proto in file_protos}
152  def _AddFile(file_proto):
153  for dependency in file_proto.dependency:
154  if dependency in file_by_name:
155  # Remove from elements to be visited, in order to cut cycles.
156  _AddFile(file_by_name.pop(dependency))
157  _FACTORY.pool.Add(file_proto)
158  while file_by_name:
159  _AddFile(file_by_name.popitem()[1])
160  return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])
google::protobuf::python::cdescriptor_pool::FindFileByName
static PyObject * FindFileByName(PyObject *self, PyObject *arg)
Definition: descriptor_pool.cc:258
google::protobuf.message_factory.MessageFactory.pool
pool
Definition: message_factory.py:61
google::protobuf.pyext
Definition: python/google/protobuf/pyext/__init__.py:1
google::protobuf
Definition: data_proto2_to_proto3_util.h:12
google::protobuf.message_factory.MessageFactory._classes
_classes
Definition: message_factory.py:64
google::protobuf.internal
Definition: python/google/protobuf/internal/__init__.py:1
google::protobuf.message_factory.GetMessages
def GetMessages(file_protos)
Definition: message_factory.py:138
google::protobuf.message_factory.MessageFactory.GetPrototype
def GetPrototype(self, descriptor)
Definition: message_factory.py:66
google::protobuf.message_factory.MessageFactory.GetMessages
def GetMessages(self, files)
Definition: message_factory.py:98
google::protobuf.descriptor_pool.DescriptorPool
Definition: descriptor_pool.py:102
google::protobuf.message_factory._GENERATED_PROTOCOL_MESSAGE_TYPE
_GENERATED_PROTOCOL_MESSAGE_TYPE
Definition: message_factory.py:53
google::protobuf.message_factory.MessageFactory.__init__
def __init__(self, pool=None)
Definition: message_factory.py:59
google::protobuf.message_factory.MessageFactory
Definition: message_factory.py:56


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:56