_runtime_protos.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright 2020 The gRPC authors.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import sys
  15. import types
  16. from typing import Tuple, Union
  17. _REQUIRED_SYMBOLS = ("_protos", "_services", "_protos_and_services")
  18. _MINIMUM_VERSION = (3, 5, 0)
  19. _UNINSTALLED_TEMPLATE = "Install the grpcio-tools package (1.32.0+) to use the {} function."
  20. _VERSION_ERROR_TEMPLATE = "The {} function is only on available on Python 3.X interpreters."
  21. def _has_runtime_proto_symbols(mod: types.ModuleType) -> bool:
  22. return all(hasattr(mod, sym) for sym in _REQUIRED_SYMBOLS)
  23. def _is_grpc_tools_importable() -> bool:
  24. try:
  25. import grpc_tools # pylint: disable=unused-import # pytype: disable=import-error
  26. return True
  27. except ImportError as e:
  28. # NOTE: It's possible that we're encountering a transitive ImportError, so
  29. # we check for that and re-raise if so.
  30. if "grpc_tools" not in e.args[0]:
  31. raise
  32. return False
  33. def _call_with_lazy_import(
  34. fn_name: str, protobuf_path: str
  35. ) -> Union[types.ModuleType, Tuple[types.ModuleType, types.ModuleType]]:
  36. """Calls one of the three functions, lazily importing grpc_tools.
  37. Args:
  38. fn_name: The name of the function to import from grpc_tools.protoc.
  39. protobuf_path: The path to import.
  40. Returns:
  41. The appropriate module object.
  42. """
  43. if sys.version_info < _MINIMUM_VERSION:
  44. raise NotImplementedError(_VERSION_ERROR_TEMPLATE.format(fn_name))
  45. else:
  46. if not _is_grpc_tools_importable():
  47. raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
  48. import grpc_tools.protoc # pytype: disable=import-error
  49. if _has_runtime_proto_symbols(grpc_tools.protoc):
  50. fn = getattr(grpc_tools.protoc, '_' + fn_name)
  51. return fn(protobuf_path)
  52. else:
  53. raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
  54. def protos(protobuf_path): # pylint: disable=unused-argument
  55. """Returns a module generated by the indicated .proto file.
  56. THIS IS AN EXPERIMENTAL API.
  57. Use this function to retrieve classes corresponding to message
  58. definitions in the .proto file.
  59. To inspect the contents of the returned module, use the dir function.
  60. For example:
  61. ```
  62. protos = grpc.protos("foo.proto")
  63. print(dir(protos))
  64. ```
  65. The returned module object corresponds to the _pb2.py file generated
  66. by protoc. The path is expected to be relative to an entry on sys.path
  67. and all transitive dependencies of the file should also be resolveable
  68. from an entry on sys.path.
  69. To completely disable the machinery behind this function, set the
  70. GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
  71. Args:
  72. protobuf_path: The path to the .proto file on the filesystem. This path
  73. must be resolveable from an entry on sys.path and so must all of its
  74. transitive dependencies.
  75. Returns:
  76. A module object corresponding to the message code for the indicated
  77. .proto file. Equivalent to a generated _pb2.py file.
  78. """
  79. return _call_with_lazy_import("protos", protobuf_path)
  80. def services(protobuf_path): # pylint: disable=unused-argument
  81. """Returns a module generated by the indicated .proto file.
  82. THIS IS AN EXPERIMENTAL API.
  83. Use this function to retrieve classes and functions corresponding to
  84. service definitions in the .proto file, including both stub and servicer
  85. definitions.
  86. To inspect the contents of the returned module, use the dir function.
  87. For example:
  88. ```
  89. services = grpc.services("foo.proto")
  90. print(dir(services))
  91. ```
  92. The returned module object corresponds to the _pb2_grpc.py file generated
  93. by protoc. The path is expected to be relative to an entry on sys.path
  94. and all transitive dependencies of the file should also be resolveable
  95. from an entry on sys.path.
  96. To completely disable the machinery behind this function, set the
  97. GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
  98. Args:
  99. protobuf_path: The path to the .proto file on the filesystem. This path
  100. must be resolveable from an entry on sys.path and so must all of its
  101. transitive dependencies.
  102. Returns:
  103. A module object corresponding to the stub/service code for the indicated
  104. .proto file. Equivalent to a generated _pb2_grpc.py file.
  105. """
  106. return _call_with_lazy_import("services", protobuf_path)
  107. def protos_and_services(protobuf_path): # pylint: disable=unused-argument
  108. """Returns a 2-tuple of modules corresponding to protos and services.
  109. THIS IS AN EXPERIMENTAL API.
  110. The return value of this function is equivalent to a call to protos and a
  111. call to services.
  112. To completely disable the machinery behind this function, set the
  113. GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
  114. Args:
  115. protobuf_path: The path to the .proto file on the filesystem. This path
  116. must be resolveable from an entry on sys.path and so must all of its
  117. transitive dependencies.
  118. Returns:
  119. A 2-tuple of module objects corresponding to (protos(path), services(path)).
  120. """
  121. return _call_with_lazy_import("protos_and_services", protobuf_path)