图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
5.4 KiB

  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. """Dynamic Protobuf class creator."""
  31. from collections import OrderedDict
  32. import hashlib
  33. import os
  34. from google.protobuf import descriptor_pb2
  35. from google.protobuf import descriptor
  36. from google.protobuf import descriptor_pool
  37. from google.protobuf import message_factory
  38. def _GetMessageFromFactory(pool, full_name):
  39. """Get a proto class from the MessageFactory by name.
  40. Args:
  41. pool: a descriptor pool.
  42. full_name: str, the fully qualified name of the proto type.
  43. Returns:
  44. A class, for the type identified by full_name.
  45. Raises:
  46. KeyError, if the proto is not found in the factory's descriptor pool.
  47. """
  48. proto_descriptor = pool.FindMessageTypeByName(full_name)
  49. proto_cls = message_factory.GetMessageClass(proto_descriptor)
  50. return proto_cls
  51. def MakeSimpleProtoClass(fields, full_name=None, pool=None):
  52. """Create a Protobuf class whose fields are basic types.
  53. Note: this doesn't validate field names!
  54. Args:
  55. fields: dict of {name: field_type} mappings for each field in the proto. If
  56. this is an OrderedDict the order will be maintained, otherwise the
  57. fields will be sorted by name.
  58. full_name: optional str, the fully-qualified name of the proto type.
  59. pool: optional DescriptorPool instance.
  60. Returns:
  61. a class, the new protobuf class with a FileDescriptor.
  62. """
  63. pool_instance = pool or descriptor_pool.DescriptorPool()
  64. if full_name is not None:
  65. try:
  66. proto_cls = _GetMessageFromFactory(pool_instance, full_name)
  67. return proto_cls
  68. except KeyError:
  69. # The factory's DescriptorPool doesn't know about this class yet.
  70. pass
  71. # Get a list of (name, field_type) tuples from the fields dict. If fields was
  72. # an OrderedDict we keep the order, but otherwise we sort the field to ensure
  73. # consistent ordering.
  74. field_items = fields.items()
  75. if not isinstance(fields, OrderedDict):
  76. field_items = sorted(field_items)
  77. # Use a consistent file name that is unlikely to conflict with any imported
  78. # proto files.
  79. fields_hash = hashlib.sha1()
  80. for f_name, f_type in field_items:
  81. fields_hash.update(f_name.encode('utf-8'))
  82. fields_hash.update(str(f_type).encode('utf-8'))
  83. proto_file_name = fields_hash.hexdigest() + '.proto'
  84. # If the proto is anonymous, use the same hash to name it.
  85. if full_name is None:
  86. full_name = ('net.proto2.python.public.proto_builder.AnonymousProto_' +
  87. fields_hash.hexdigest())
  88. try:
  89. proto_cls = _GetMessageFromFactory(pool_instance, full_name)
  90. return proto_cls
  91. except KeyError:
  92. # The factory's DescriptorPool doesn't know about this class yet.
  93. pass
  94. # This is the first time we see this proto: add a new descriptor to the pool.
  95. pool_instance.Add(
  96. _MakeFileDescriptorProto(proto_file_name, full_name, field_items))
  97. return _GetMessageFromFactory(pool_instance, full_name)
  98. def _MakeFileDescriptorProto(proto_file_name, full_name, field_items):
  99. """Populate FileDescriptorProto for MessageFactory's DescriptorPool."""
  100. package, name = full_name.rsplit('.', 1)
  101. file_proto = descriptor_pb2.FileDescriptorProto()
  102. file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name)
  103. file_proto.package = package
  104. desc_proto = file_proto.message_type.add()
  105. desc_proto.name = name
  106. for f_number, (f_name, f_type) in enumerate(field_items, 1):
  107. field_proto = desc_proto.field.add()
  108. field_proto.name = f_name
  109. # # If the number falls in the reserved range, reassign it to the correct
  110. # # number after the range.
  111. if f_number >= descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER:
  112. f_number += (
  113. descriptor.FieldDescriptor.LAST_RESERVED_FIELD_NUMBER -
  114. descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER + 1)
  115. field_proto.number = f_number
  116. field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
  117. field_proto.type = f_type
  118. return file_proto