symbol_database.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. """A database of Python protocol buffer generated symbols.
  31. SymbolDatabase makes it easy to create new instances of a registered type, given
  32. only the type's protocol buffer symbol name. Once all symbols are registered,
  33. they can be accessed using either the MessageFactory interface which
  34. SymbolDatabase exposes, or the DescriptorPool interface of the underlying
  35. pool.
  36. Example usage:
  37. db = symbol_database.SymbolDatabase()
  38. # Register symbols of interest, from one or multiple files.
  39. db.RegisterFileDescriptor(my_proto_pb2.DESCRIPTOR)
  40. db.RegisterMessage(my_proto_pb2.MyMessage)
  41. db.RegisterEnumDescriptor(my_proto_pb2.MyEnum.DESCRIPTOR)
  42. # The database can be used as a MessageFactory, to generate types based on
  43. # their name:
  44. types = db.GetMessages(['my_proto.proto'])
  45. my_message_instance = types['MyMessage']()
  46. # The database's underlying descriptor pool can be queried, so it's not
  47. # necessary to know a type's filename to be able to generate it:
  48. filename = db.pool.FindFileContainingSymbol('MyMessage')
  49. my_message_instance = db.GetMessages([filename])['MyMessage']()
  50. # This functionality is also provided directly via a convenience method:
  51. my_message_instance = db.GetSymbol('MyMessage')()
  52. """
  53. from google.protobuf import descriptor_pool
  54. class SymbolDatabase(object):
  55. """A database of Python generated symbols.
  56. SymbolDatabase also models message_factory.MessageFactory.
  57. The symbol database can be used to keep a global registry of all protocol
  58. buffer types used within a program.
  59. """
  60. def __init__(self):
  61. """Constructor."""
  62. self._symbols = {}
  63. self._symbols_by_file = {}
  64. self.pool = descriptor_pool.DescriptorPool()
  65. def RegisterMessage(self, message):
  66. """Registers the given message type in the local database.
  67. Args:
  68. message: a message.Message, to be registered.
  69. Returns:
  70. The provided message.
  71. """
  72. desc = message.DESCRIPTOR
  73. self._symbols[desc.full_name] = message
  74. if desc.file.name not in self._symbols_by_file:
  75. self._symbols_by_file[desc.file.name] = {}
  76. self._symbols_by_file[desc.file.name][desc.full_name] = message
  77. self.pool.AddDescriptor(desc)
  78. return message
  79. def RegisterEnumDescriptor(self, enum_descriptor):
  80. """Registers the given enum descriptor in the local database.
  81. Args:
  82. enum_descriptor: a descriptor.EnumDescriptor.
  83. Returns:
  84. The provided descriptor.
  85. """
  86. self.pool.AddEnumDescriptor(enum_descriptor)
  87. return enum_descriptor
  88. def RegisterFileDescriptor(self, file_descriptor):
  89. """Registers the given file descriptor in the local database.
  90. Args:
  91. file_descriptor: a descriptor.FileDescriptor.
  92. Returns:
  93. The provided descriptor.
  94. """
  95. self.pool.AddFileDescriptor(file_descriptor)
  96. def GetSymbol(self, symbol):
  97. """Tries to find a symbol in the local database.
  98. Currently, this method only returns message.Message instances, however, if
  99. may be extended in future to support other symbol types.
  100. Args:
  101. symbol: A str, a protocol buffer symbol.
  102. Returns:
  103. A Python class corresponding to the symbol.
  104. Raises:
  105. KeyError: if the symbol could not be found.
  106. """
  107. return self._symbols[symbol]
  108. def GetPrototype(self, descriptor):
  109. """Builds a proto2 message class based on the passed in descriptor.
  110. Passing a descriptor with a fully qualified name matching a previous
  111. invocation will cause the same class to be returned.
  112. Args:
  113. descriptor: The descriptor to build from.
  114. Returns:
  115. A class describing the passed in descriptor.
  116. """
  117. return self.GetSymbol(descriptor.full_name)
  118. def GetMessages(self, files):
  119. """Gets all the messages from a specified file.
  120. This will find and resolve dependencies, failing if they are not registered
  121. in the symbol database.
  122. Args:
  123. files: The file names to extract messages from.
  124. Returns:
  125. A dictionary mapping proto names to the message classes. This will include
  126. any dependent messages as well as any messages defined in the same file as
  127. a specified message.
  128. Raises:
  129. KeyError: if a file could not be found.
  130. """
  131. result = {}
  132. for f in files:
  133. result.update(self._symbols_by_file[f])
  134. return result
  135. _DEFAULT = SymbolDatabase()
  136. def Default():
  137. """Returns the default SymbolDatabase."""
  138. return _DEFAULT