message_factory.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. #PY25 compatible for GAE.
  31. #
  32. # Copyright 2012 Google Inc. All Rights Reserved.
  33. """Provides a factory class for generating dynamic messages.
  34. The easiest way to use this class is if you have access to the FileDescriptor
  35. protos containing the messages you want to create you can just do the following:
  36. message_classes = message_factory.GetMessages(iterable_of_file_descriptors)
  37. my_proto_instance = message_classes['some.proto.package.MessageName']()
  38. """
  39. __author__ = 'matthewtoia@google.com (Matt Toia)'
  40. import sys ##PY25
  41. from google.protobuf import descriptor_database
  42. from google.protobuf import descriptor_pool
  43. from google.protobuf import message
  44. from google.protobuf import reflection
  45. class MessageFactory(object):
  46. """Factory for creating Proto2 messages from descriptors in a pool."""
  47. def __init__(self, pool=None):
  48. """Initializes a new factory."""
  49. self.pool = (pool or descriptor_pool.DescriptorPool(
  50. descriptor_database.DescriptorDatabase()))
  51. # local cache of all classes built from protobuf descriptors
  52. self._classes = {}
  53. def GetPrototype(self, descriptor):
  54. """Builds a proto2 message class based on the passed in descriptor.
  55. Passing a descriptor with a fully qualified name matching a previous
  56. invocation will cause the same class to be returned.
  57. Args:
  58. descriptor: The descriptor to build from.
  59. Returns:
  60. A class describing the passed in descriptor.
  61. """
  62. if descriptor.full_name not in self._classes:
  63. descriptor_name = descriptor.name
  64. if sys.version_info[0] < 3: ##PY25
  65. ##!PY25 if str is bytes: # PY2
  66. descriptor_name = descriptor.name.encode('ascii', 'ignore')
  67. result_class = reflection.GeneratedProtocolMessageType(
  68. descriptor_name,
  69. (message.Message,),
  70. {'DESCRIPTOR': descriptor, '__module__': None})
  71. # If module not set, it wrongly points to the reflection.py module.
  72. self._classes[descriptor.full_name] = result_class
  73. for field in descriptor.fields:
  74. if field.message_type:
  75. self.GetPrototype(field.message_type)
  76. for extension in result_class.DESCRIPTOR.extensions:
  77. if extension.containing_type.full_name not in self._classes:
  78. self.GetPrototype(extension.containing_type)
  79. extended_class = self._classes[extension.containing_type.full_name]
  80. extended_class.RegisterExtension(extension)
  81. return self._classes[descriptor.full_name]
  82. def GetMessages(self, files):
  83. """Gets all the messages from a specified file.
  84. This will find and resolve dependencies, failing if the descriptor
  85. pool cannot satisfy them.
  86. Args:
  87. files: The file names to extract messages from.
  88. Returns:
  89. A dictionary mapping proto names to the message classes. This will include
  90. any dependent messages as well as any messages defined in the same file as
  91. a specified message.
  92. """
  93. result = {}
  94. for file_name in files:
  95. file_desc = self.pool.FindFileByName(file_name)
  96. for name, msg in file_desc.message_types_by_name.iteritems():
  97. if file_desc.package:
  98. full_name = '.'.join([file_desc.package, name])
  99. else:
  100. full_name = msg.name
  101. result[full_name] = self.GetPrototype(
  102. self.pool.FindMessageTypeByName(full_name))
  103. # While the extension FieldDescriptors are created by the descriptor pool,
  104. # the python classes created in the factory need them to be registered
  105. # explicitly, which is done below.
  106. #
  107. # The call to RegisterExtension will specifically check if the
  108. # extension was already registered on the object and either
  109. # ignore the registration if the original was the same, or raise
  110. # an error if they were different.
  111. for name, extension in file_desc.extensions_by_name.iteritems():
  112. if extension.containing_type.full_name not in self._classes:
  113. self.GetPrototype(extension.containing_type)
  114. extended_class = self._classes[extension.containing_type.full_name]
  115. extended_class.RegisterExtension(extension)
  116. return result
  117. _FACTORY = MessageFactory()
  118. def GetMessages(file_protos):
  119. """Builds a dictionary of all the messages available in a set of files.
  120. Args:
  121. file_protos: A sequence of file protos to build messages out of.
  122. Returns:
  123. A dictionary mapping proto names to the message classes. This will include
  124. any dependent messages as well as any messages defined in the same file as
  125. a specified message.
  126. """
  127. for file_proto in file_protos:
  128. _FACTORY.pool.Add(file_proto)
  129. return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])