图片解析应用
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.

163 lines
6.0 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. """Determine which implementation of the protobuf API is used in this process.
  31. """
  32. import importlib
  33. import os
  34. import sys
  35. import warnings
  36. def _ApiVersionToImplementationType(api_version):
  37. if api_version == 2:
  38. return 'cpp'
  39. if api_version == 1:
  40. raise ValueError('api_version=1 is no longer supported.')
  41. if api_version == 0:
  42. return 'python'
  43. return None
  44. _implementation_type = None
  45. try:
  46. # pylint: disable=g-import-not-at-top
  47. from google.protobuf.internal import _api_implementation
  48. # The compile-time constants in the _api_implementation module can be used to
  49. # switch to a certain implementation of the Python API at build time.
  50. _implementation_type = _ApiVersionToImplementationType(
  51. _api_implementation.api_version)
  52. except ImportError:
  53. pass # Unspecified by compiler flags.
  54. def _CanImport(mod_name):
  55. try:
  56. mod = importlib.import_module(mod_name)
  57. # Work around a known issue in the classic bootstrap .par import hook.
  58. if not mod:
  59. raise ImportError(mod_name + ' import succeeded but was None')
  60. return True
  61. except ImportError:
  62. return False
  63. if _implementation_type is None:
  64. if _CanImport('google._upb._message'):
  65. _implementation_type = 'upb'
  66. elif _CanImport('google.protobuf.pyext._message'):
  67. _implementation_type = 'cpp'
  68. else:
  69. _implementation_type = 'python'
  70. # This environment variable can be used to switch to a certain implementation
  71. # of the Python API, overriding the compile-time constants in the
  72. # _api_implementation module. Right now only 'python', 'cpp' and 'upb' are
  73. # valid values. Any other value will raise error.
  74. _implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION',
  75. _implementation_type)
  76. if _implementation_type not in ('python', 'cpp', 'upb'):
  77. raise ValueError('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION {0} is not '
  78. 'supported. Please set to \'python\', \'cpp\' or '
  79. '\'upb\'.'.format(_implementation_type))
  80. if 'PyPy' in sys.version and _implementation_type == 'cpp':
  81. warnings.warn('PyPy does not work yet with cpp protocol buffers. '
  82. 'Falling back to the python implementation.')
  83. _implementation_type = 'python'
  84. _c_module = None
  85. if _implementation_type == 'cpp':
  86. try:
  87. # pylint: disable=g-import-not-at-top
  88. from google.protobuf.pyext import _message
  89. sys.modules['google3.net.proto2.python.internal.cpp._message'] = _message
  90. _c_module = _message
  91. del _message
  92. except ImportError:
  93. # TODO(jieluo): fail back to python
  94. warnings.warn(
  95. 'Selected implementation cpp is not available.')
  96. pass
  97. if _implementation_type == 'upb':
  98. try:
  99. # pylint: disable=g-import-not-at-top
  100. from google._upb import _message
  101. _c_module = _message
  102. del _message
  103. except ImportError:
  104. warnings.warn('Selected implementation upb is not available. '
  105. 'Falling back to the python implementation.')
  106. _implementation_type = 'python'
  107. pass
  108. # Detect if serialization should be deterministic by default
  109. try:
  110. # The presence of this module in a build allows the proto implementation to
  111. # be upgraded merely via build deps.
  112. #
  113. # NOTE: Merely importing this automatically enables deterministic proto
  114. # serialization for C++ code, but we still need to export it as a boolean so
  115. # that we can do the same for `_implementation_type == 'python'`.
  116. #
  117. # NOTE2: It is possible for C++ code to enable deterministic serialization by
  118. # default _without_ affecting Python code, if the C++ implementation is not in
  119. # use by this module. That is intended behavior, so we don't actually expose
  120. # this boolean outside of this module.
  121. #
  122. # pylint: disable=g-import-not-at-top,unused-import
  123. from google.protobuf import enable_deterministic_proto_serialization
  124. _python_deterministic_proto_serialization = True
  125. except ImportError:
  126. _python_deterministic_proto_serialization = False
  127. # Usage of this function is discouraged. Clients shouldn't care which
  128. # implementation of the API is in use. Note that there is no guarantee
  129. # that differences between APIs will be maintained.
  130. # Please don't use this function if possible.
  131. def Type():
  132. return _implementation_type
  133. # See comment on 'Type' above.
  134. # TODO(jieluo): Remove the API, it returns a constant. b/228102101
  135. def Version():
  136. return 2
  137. # For internal use only
  138. def IsPythonDefaultSerializationDeterministic():
  139. return _python_deterministic_proto_serialization