店播爬取Python脚本

message_factory.py 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. """Provides a factory class for generating dynamic messages.
  31. The easiest way to use this class is if you have access to the FileDescriptor
  32. protos containing the messages you want to create you can just do the following:
  33. message_classes = message_factory.GetMessages(iterable_of_file_descriptors)
  34. my_proto_instance = message_classes['some.proto.package.MessageName']()
  35. """
  36. __author__ = 'matthewtoia@google.com (Matt Toia)'
  37. from google.protobuf.internal import api_implementation
  38. from google.protobuf import descriptor_pool
  39. from google.protobuf import message
  40. if api_implementation.Type() == 'cpp':
  41. from google.protobuf.pyext import cpp_message as message_impl
  42. else:
  43. from google.protobuf.internal import python_message as message_impl
  44. # The type of all Message classes.
  45. _GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType
  46. class MessageFactory(object):
  47. """Factory for creating Proto2 messages from descriptors in a pool."""
  48. def __init__(self, pool=None):
  49. """Initializes a new factory."""
  50. self.pool = pool or descriptor_pool.DescriptorPool()
  51. # local cache of all classes built from protobuf descriptors
  52. self._classes = {}
  53. def GetPrototype(self, descriptor):
  54. """Obtains 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 not in self._classes:
  63. result_class = self.CreatePrototype(descriptor)
  64. # The assignment to _classes is redundant for the base implementation, but
  65. # might avoid confusion in cases where CreatePrototype gets overridden and
  66. # does not call the base implementation.
  67. self._classes[descriptor] = result_class
  68. return result_class
  69. return self._classes[descriptor]
  70. def CreatePrototype(self, descriptor):
  71. """Builds a proto2 message class based on the passed in descriptor.
  72. Don't call this function directly, it always creates a new class. Call
  73. GetPrototype() instead. This method is meant to be overridden in subblasses
  74. to perform additional operations on the newly constructed class.
  75. Args:
  76. descriptor: The descriptor to build from.
  77. Returns:
  78. A class describing the passed in descriptor.
  79. """
  80. descriptor_name = descriptor.name
  81. if str is bytes: # PY2
  82. descriptor_name = descriptor.name.encode('ascii', 'ignore')
  83. result_class = _GENERATED_PROTOCOL_MESSAGE_TYPE(
  84. descriptor_name,
  85. (message.Message,),
  86. {
  87. 'DESCRIPTOR': descriptor,
  88. # If module not set, it wrongly points to message_factory module.
  89. '__module__': None,
  90. })
  91. result_class._FACTORY = self # pylint: disable=protected-access
  92. # Assign in _classes before doing recursive calls to avoid infinite
  93. # recursion.
  94. self._classes[descriptor] = result_class
  95. for field in descriptor.fields:
  96. if field.message_type:
  97. self.GetPrototype(field.message_type)
  98. for extension in result_class.DESCRIPTOR.extensions:
  99. if extension.containing_type not in self._classes:
  100. self.GetPrototype(extension.containing_type)
  101. extended_class = self._classes[extension.containing_type]
  102. extended_class.RegisterExtension(extension)
  103. return result_class
  104. def GetMessages(self, files):
  105. """Gets all the messages from a specified file.
  106. This will find and resolve dependencies, failing if the descriptor
  107. pool cannot satisfy them.
  108. Args:
  109. files: The file names to extract messages from.
  110. Returns:
  111. A dictionary mapping proto names to the message classes. This will include
  112. any dependent messages as well as any messages defined in the same file as
  113. a specified message.
  114. """
  115. result = {}
  116. for file_name in files:
  117. file_desc = self.pool.FindFileByName(file_name)
  118. for desc in file_desc.message_types_by_name.values():
  119. result[desc.full_name] = self.GetPrototype(desc)
  120. # While the extension FieldDescriptors are created by the descriptor pool,
  121. # the python classes created in the factory need them to be registered
  122. # explicitly, which is done below.
  123. #
  124. # The call to RegisterExtension will specifically check if the
  125. # extension was already registered on the object and either
  126. # ignore the registration if the original was the same, or raise
  127. # an error if they were different.
  128. for extension in file_desc.extensions_by_name.values():
  129. if extension.containing_type not in self._classes:
  130. self.GetPrototype(extension.containing_type)
  131. extended_class = self._classes[extension.containing_type]
  132. extended_class.RegisterExtension(extension)
  133. return result
  134. _FACTORY = MessageFactory()
  135. def GetMessages(file_protos):
  136. """Builds a dictionary of all the messages available in a set of files.
  137. Args:
  138. file_protos: Iterable of FileDescriptorProto to build messages out of.
  139. Returns:
  140. A dictionary mapping proto names to the message classes. This will include
  141. any dependent messages as well as any messages defined in the same file as
  142. a specified message.
  143. """
  144. # The cpp implementation of the protocol buffer library requires to add the
  145. # message in topological order of the dependency graph.
  146. file_by_name = {file_proto.name: file_proto for file_proto in file_protos}
  147. def _AddFile(file_proto):
  148. for dependency in file_proto.dependency:
  149. if dependency in file_by_name:
  150. # Remove from elements to be visited, in order to cut cycles.
  151. _AddFile(file_by_name.pop(dependency))
  152. _FACTORY.pool.Add(file_proto)
  153. while file_by_name:
  154. _AddFile(file_by_name.popitem()[1])
  155. return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])