aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/python/grpcio/grpc/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'src/python/grpcio/grpc/__init__.py')
-rw-r--r--src/python/grpcio/grpc/__init__.py744
1 files changed, 381 insertions, 363 deletions
diff --git a/src/python/grpcio/grpc/__init__.py b/src/python/grpcio/grpc/__init__.py
index e3c10156d0..abe14e7049 100644
--- a/src/python/grpcio/grpc/__init__.py
+++ b/src/python/grpcio/grpc/__init__.py
@@ -26,7 +26,6 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
"""gRPC's Python API."""
import abc
@@ -37,28 +36,27 @@ import six
from grpc._cython import cygrpc as _cygrpc
-
############################## Future Interface ###############################
class FutureTimeoutError(Exception):
- """Indicates that a method call on a Future timed out."""
+ """Indicates that a method call on a Future timed out."""
class FutureCancelledError(Exception):
- """Indicates that the computation underlying a Future was cancelled."""
+ """Indicates that the computation underlying a Future was cancelled."""
class Future(six.with_metaclass(abc.ABCMeta)):
- """A representation of a computation in another control flow.
+ """A representation of a computation in another control flow.
Computations represented by a Future may be yet to be begun, may be ongoing,
or may have already completed.
"""
- @abc.abstractmethod
- def cancel(self):
- """Attempts to cancel the computation.
+ @abc.abstractmethod
+ def cancel(self):
+ """Attempts to cancel the computation.
This method does not block.
@@ -71,11 +69,11 @@ class Future(six.with_metaclass(abc.ABCMeta)):
remote system for which a determination of whether or not it commenced
before being cancelled cannot be made without blocking.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def cancelled(self):
- """Describes whether the computation was cancelled.
+ @abc.abstractmethod
+ def cancelled(self):
+ """Describes whether the computation was cancelled.
This method does not block.
@@ -85,11 +83,11 @@ class Future(six.with_metaclass(abc.ABCMeta)):
not limited to this object's cancel method not having been called and
the computation's result having become immediately available.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def running(self):
- """Describes whether the computation is taking place.
+ @abc.abstractmethod
+ def running(self):
+ """Describes whether the computation is taking place.
This method does not block.
@@ -98,11 +96,11 @@ class Future(six.with_metaclass(abc.ABCMeta)):
taking place now, or False if the computation took place in the past or
was cancelled.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def done(self):
- """Describes whether the computation has taken place.
+ @abc.abstractmethod
+ def done(self):
+ """Describes whether the computation has taken place.
This method does not block.
@@ -111,11 +109,11 @@ class Future(six.with_metaclass(abc.ABCMeta)):
unscheduled or interrupted. False if the computation may possibly be
executing or scheduled to execute later.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def result(self, timeout=None):
- """Accesses the outcome of the computation or raises its exception.
+ @abc.abstractmethod
+ def result(self, timeout=None):
+ """Accesses the outcome of the computation or raises its exception.
This method may return immediately or may block.
@@ -134,11 +132,11 @@ class Future(six.with_metaclass(abc.ABCMeta)):
Exception: If the computation raised an exception, this call will raise
the same exception.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def exception(self, timeout=None):
- """Return the exception raised by the computation.
+ @abc.abstractmethod
+ def exception(self, timeout=None):
+ """Return the exception raised by the computation.
This method may return immediately or may block.
@@ -157,11 +155,11 @@ class Future(six.with_metaclass(abc.ABCMeta)):
not terminate within the allotted time.
FutureCancelledError: If the computation was cancelled.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def traceback(self, timeout=None):
- """Access the traceback of the exception raised by the computation.
+ @abc.abstractmethod
+ def traceback(self, timeout=None):
+ """Access the traceback of the exception raised by the computation.
This method may return immediately or may block.
@@ -180,11 +178,11 @@ class Future(six.with_metaclass(abc.ABCMeta)):
not terminate within the allotted time.
FutureCancelledError: If the computation was cancelled.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def add_done_callback(self, fn):
- """Adds a function to be called at completion of the computation.
+ @abc.abstractmethod
+ def add_done_callback(self, fn):
+ """Adds a function to be called at completion of the computation.
The callback will be passed this Future object describing the outcome of
the computation.
@@ -195,7 +193,7 @@ class Future(six.with_metaclass(abc.ABCMeta)):
Args:
fn: A callable taking this Future object as its single parameter.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
################################ gRPC Enums ##################################
@@ -203,7 +201,7 @@ class Future(six.with_metaclass(abc.ABCMeta)):
@enum.unique
class ChannelConnectivity(enum.Enum):
- """Mirrors grpc_connectivity_state in the gRPC Core.
+ """Mirrors grpc_connectivity_state in the gRPC Core.
Attributes:
IDLE: The channel is idle.
@@ -213,81 +211,80 @@ class ChannelConnectivity(enum.Enum):
recover.
SHUTDOWN: The channel has seen a failure from which it cannot recover.
"""
- IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
- CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
- READY = (_cygrpc.ConnectivityState.ready, 'ready')
- TRANSIENT_FAILURE = (
- _cygrpc.ConnectivityState.transient_failure, 'transient failure')
- SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
+ IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
+ CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
+ READY = (_cygrpc.ConnectivityState.ready, 'ready')
+ TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure,
+ 'transient failure')
+ SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
@enum.unique
class StatusCode(enum.Enum):
- """Mirrors grpc_status_code in the gRPC Core."""
- OK = (_cygrpc.StatusCode.ok, 'ok')
- CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
- UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
- INVALID_ARGUMENT = (
- _cygrpc.StatusCode.invalid_argument, 'invalid argument')
- DEADLINE_EXCEEDED = (
- _cygrpc.StatusCode.deadline_exceeded, 'deadline exceeded')
- NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
- ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
- PERMISSION_DENIED = (
- _cygrpc.StatusCode.permission_denied, 'permission denied')
- RESOURCE_EXHAUSTED = (
- _cygrpc.StatusCode.resource_exhausted, 'resource exhausted')
- FAILED_PRECONDITION = (
- _cygrpc.StatusCode.failed_precondition, 'failed precondition')
- ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
- OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
- UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
- INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
- UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
- DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
- UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
+ """Mirrors grpc_status_code in the gRPC Core."""
+ OK = (_cygrpc.StatusCode.ok, 'ok')
+ CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
+ UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
+ INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument')
+ DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded,
+ 'deadline exceeded')
+ NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
+ ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
+ PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied,
+ 'permission denied')
+ RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted,
+ 'resource exhausted')
+ FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition,
+ 'failed precondition')
+ ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
+ OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
+ UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
+ INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
+ UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
+ DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
+ UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
############################# gRPC Exceptions ################################
class RpcError(Exception):
- """Raised by the gRPC library to indicate non-OK-status RPC termination."""
+ """Raised by the gRPC library to indicate non-OK-status RPC termination."""
############################## Shared Context ################################
class RpcContext(six.with_metaclass(abc.ABCMeta)):
- """Provides RPC-related information and action."""
+ """Provides RPC-related information and action."""
- @abc.abstractmethod
- def is_active(self):
- """Describes whether the RPC is active or has terminated."""
- raise NotImplementedError()
+ @abc.abstractmethod
+ def is_active(self):
+ """Describes whether the RPC is active or has terminated."""
+ raise NotImplementedError()
- @abc.abstractmethod
- def time_remaining(self):
- """Describes the length of allowed time remaining for the RPC.
+ @abc.abstractmethod
+ def time_remaining(self):
+ """Describes the length of allowed time remaining for the RPC.
Returns:
A nonnegative float indicating the length of allowed time in seconds
remaining for the RPC to complete before it is considered to have timed
out, or None if no deadline was specified for the RPC.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def cancel(self):
- """Cancels the RPC.
+ @abc.abstractmethod
+ def cancel(self):
+ """Cancels the RPC.
Idempotent and has no effect if the RPC has already terminated.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def add_callback(self, callback):
- """Registers a callback to be called on RPC termination.
+ @abc.abstractmethod
+ def add_callback(self, callback):
+ """Registers a callback to be called on RPC termination.
Args:
callback: A no-parameter callable to be called on RPC termination.
@@ -297,76 +294,76 @@ class RpcContext(six.with_metaclass(abc.ABCMeta)):
callback was not added and will not later be called (because the RPC
already terminated or some other reason).
"""
- raise NotImplementedError()
+ raise NotImplementedError()
######################### Invocation-Side Context ############################
class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
- """Invocation-side utility object for an RPC."""
+ """Invocation-side utility object for an RPC."""
- @abc.abstractmethod
- def initial_metadata(self):
- """Accesses the initial metadata from the service-side of the RPC.
+ @abc.abstractmethod
+ def initial_metadata(self):
+ """Accesses the initial metadata from the service-side of the RPC.
This method blocks until the value is available.
Returns:
The initial :term:`metadata`.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def trailing_metadata(self):
- """Accesses the trailing metadata from the service-side of the RPC.
+ @abc.abstractmethod
+ def trailing_metadata(self):
+ """Accesses the trailing metadata from the service-side of the RPC.
This method blocks until the value is available.
Returns:
The trailing :term:`metadata`.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def code(self):
- """Accesses the status code emitted by the service-side of the RPC.
+ @abc.abstractmethod
+ def code(self):
+ """Accesses the status code emitted by the service-side of the RPC.
This method blocks until the value is available.
Returns:
The StatusCode value for the RPC.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def details(self):
- """Accesses the details value emitted by the service-side of the RPC.
+ @abc.abstractmethod
+ def details(self):
+ """Accesses the details value emitted by the service-side of the RPC.
This method blocks until the value is available.
Returns:
The details string of the RPC.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
############ Authentication & Authorization Interfaces & Classes #############
class ChannelCredentials(object):
- """A value encapsulating the data required to create a secure Channel.
+ """A value encapsulating the data required to create a secure Channel.
This class has no supported interface - it exists to define the type of its
instances and its instances exist to be passed to other functions.
"""
- def __init__(self, credentials):
- self._credentials = credentials
+ def __init__(self, credentials):
+ self._credentials = credentials
class CallCredentials(object):
- """A value encapsulating data asserting an identity over a channel.
+ """A value encapsulating data asserting an identity over a channel.
A CallCredentials may be composed with ChannelCredentials to always assert
identity for every call over that Channel.
@@ -375,12 +372,12 @@ class CallCredentials(object):
instances and its instances exist to be passed to other functions.
"""
- def __init__(self, credentials):
- self._credentials = credentials
+ def __init__(self, credentials):
+ self._credentials = credentials
class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
- """Provides information to call credentials metadata plugins.
+ """Provides information to call credentials metadata plugins.
Attributes:
service_url: A string URL of the service being called into.
@@ -389,23 +386,23 @@ class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
- """Callback object received by a metadata plugin."""
+ """Callback object received by a metadata plugin."""
- def __call__(self, metadata, error):
- """Inform the gRPC runtime of the metadata to construct a CallCredentials.
+ def __call__(self, metadata, error):
+ """Inform the gRPC runtime of the metadata to construct a CallCredentials.
Args:
metadata: The :term:`metadata` used to construct the CallCredentials.
error: An Exception to indicate error or None to indicate success.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
- """A specification for custom authentication."""
+ """A specification for custom authentication."""
- def __call__(self, context, callback):
- """Implements authentication by passing metadata to a callback.
+ def __call__(self, context, callback):
+ """Implements authentication by passing metadata to a callback.
Implementations of this method must not block.
@@ -415,29 +412,29 @@ class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
callback: An AuthMetadataPluginCallback to be invoked either synchronously
or asynchronously.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
class ServerCredentials(object):
- """A value encapsulating the data required to open a secure port on a Server.
+ """A value encapsulating the data required to open a secure port on a Server.
This class has no supported interface - it exists to define the type of its
instances and its instances exist to be passed to other functions.
"""
- def __init__(self, credentials):
- self._credentials = credentials
+ def __init__(self, credentials):
+ self._credentials = credentials
######################## Multi-Callable Interfaces ###########################
class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a unary-unary RPC."""
+ """Affords invoking a unary-unary RPC."""
- @abc.abstractmethod
- def __call__(self, request, timeout=None, metadata=None, credentials=None):
- """Synchronously invokes the underlying RPC.
+ @abc.abstractmethod
+ def __call__(self, request, timeout=None, metadata=None, credentials=None):
+ """Synchronously invokes the underlying RPC.
Args:
request: The request value for the RPC.
@@ -454,11 +451,11 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
raised RpcError will also be a Call for the RPC affording the RPC's
metadata, status code, and details.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def with_call(self, request, timeout=None, metadata=None, credentials=None):
- """Synchronously invokes the underlying RPC.
+ @abc.abstractmethod
+ def with_call(self, request, timeout=None, metadata=None, credentials=None):
+ """Synchronously invokes the underlying RPC.
Args:
request: The request value for the RPC.
@@ -475,11 +472,11 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
raised RpcError will also be a Call for the RPC affording the RPC's
metadata, status code, and details.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def future(self, request, timeout=None, metadata=None, credentials=None):
- """Asynchronously invokes the underlying RPC.
+ @abc.abstractmethod
+ def future(self, request, timeout=None, metadata=None, credentials=None):
+ """Asynchronously invokes the underlying RPC.
Args:
request: The request value for the RPC.
@@ -494,15 +491,15 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
message of the RPC. Should the event terminate with non-OK status, the
returned Future's exception value will be an RpcError.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a unary-stream RPC."""
+ """Affords invoking a unary-stream RPC."""
- @abc.abstractmethod
- def __call__(self, request, timeout=None, metadata=None, credentials=None):
- """Invokes the underlying RPC.
+ @abc.abstractmethod
+ def __call__(self, request, timeout=None, metadata=None, credentials=None):
+ """Invokes the underlying RPC.
Args:
request: The request value for the RPC.
@@ -516,16 +513,19 @@ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
values. Drawing response values from the returned iterator may raise
RpcError indicating termination of the RPC with non-OK status.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a stream-unary RPC in any call style."""
+ """Affords invoking a stream-unary RPC in any call style."""
- @abc.abstractmethod
- def __call__(
- self, request_iterator, timeout=None, metadata=None, credentials=None):
- """Synchronously invokes the underlying RPC.
+ @abc.abstractmethod
+ def __call__(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ """Synchronously invokes the underlying RPC.
Args:
request_iterator: An iterator that yields request values for the RPC.
@@ -543,12 +543,15 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
raised RpcError will also be a Call for the RPC affording the RPC's
metadata, status code, and details.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def with_call(
- self, request_iterator, timeout=None, metadata=None, credentials=None):
- """Synchronously invokes the underlying RPC.
+ @abc.abstractmethod
+ def with_call(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ """Synchronously invokes the underlying RPC.
Args:
request_iterator: An iterator that yields request values for the RPC.
@@ -565,12 +568,15 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
raised RpcError will also be a Call for the RPC affording the RPC's
metadata, status code, and details.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def future(
- self, request_iterator, timeout=None, metadata=None, credentials=None):
- """Asynchronously invokes the underlying RPC.
+ @abc.abstractmethod
+ def future(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ """Asynchronously invokes the underlying RPC.
Args:
request_iterator: An iterator that yields request values for the RPC.
@@ -585,16 +591,19 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
message of the RPC. Should the event terminate with non-OK status, the
returned Future's exception value will be an RpcError.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a stream-stream RPC in any call style."""
+ """Affords invoking a stream-stream RPC in any call style."""
- @abc.abstractmethod
- def __call__(
- self, request_iterator, timeout=None, metadata=None, credentials=None):
- """Invokes the underlying RPC.
+ @abc.abstractmethod
+ def __call__(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ """Invokes the underlying RPC.
Args:
request_iterator: An iterator that yields request values for the RPC.
@@ -608,18 +617,18 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
values. Drawing response values from the returned iterator may raise
RpcError indicating termination of the RPC with non-OK status.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
############################# Channel Interface ##############################
class Channel(six.with_metaclass(abc.ABCMeta)):
- """Affords RPC invocation via generic methods."""
+ """Affords RPC invocation via generic methods."""
- @abc.abstractmethod
- def subscribe(self, callback, try_to_connect=False):
- """Subscribes to this Channel's connectivity.
+ @abc.abstractmethod
+ def subscribe(self, callback, try_to_connect=False):
+ """Subscribes to this Channel's connectivity.
Args:
callback: A callable to be invoked and passed a ChannelConnectivity value
@@ -631,22 +640,24 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
attempt to connect if it is not already connected and ready to conduct
RPCs.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def unsubscribe(self, callback):
- """Unsubscribes a callback from this Channel's connectivity.
+ @abc.abstractmethod
+ def unsubscribe(self, callback):
+ """Unsubscribes a callback from this Channel's connectivity.
Args:
callback: A callable previously registered with this Channel from having
been passed to its "subscribe" method.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def unary_unary(
- self, method, request_serializer=None, response_deserializer=None):
- """Creates a UnaryUnaryMultiCallable for a unary-unary method.
+ @abc.abstractmethod
+ def unary_unary(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ """Creates a UnaryUnaryMultiCallable for a unary-unary method.
Args:
method: The name of the RPC method.
@@ -658,12 +669,14 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
Returns:
A UnaryUnaryMultiCallable value for the named unary-unary method.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def unary_stream(
- self, method, request_serializer=None, response_deserializer=None):
- """Creates a UnaryStreamMultiCallable for a unary-stream method.
+ @abc.abstractmethod
+ def unary_stream(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ """Creates a UnaryStreamMultiCallable for a unary-stream method.
Args:
method: The name of the RPC method.
@@ -675,12 +688,14 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
Returns:
A UnaryStreamMultiCallable value for the name unary-stream method.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def stream_unary(
- self, method, request_serializer=None, response_deserializer=None):
- """Creates a StreamUnaryMultiCallable for a stream-unary method.
+ @abc.abstractmethod
+ def stream_unary(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ """Creates a StreamUnaryMultiCallable for a stream-unary method.
Args:
method: The name of the RPC method.
@@ -692,12 +707,14 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
Returns:
A StreamUnaryMultiCallable value for the named stream-unary method.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def stream_stream(
- self, method, request_serializer=None, response_deserializer=None):
- """Creates a StreamStreamMultiCallable for a stream-stream method.
+ @abc.abstractmethod
+ def stream_stream(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ """Creates a StreamStreamMultiCallable for a stream-stream method.
Args:
method: The name of the RPC method.
@@ -709,36 +726,36 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
Returns:
A StreamStreamMultiCallable value for the named stream-stream method.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
########################## Service-Side Context ##############################
class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
- """A context object passed to method implementations."""
+ """A context object passed to method implementations."""
- @abc.abstractmethod
- def invocation_metadata(self):
- """Accesses the metadata from the invocation-side of the RPC.
+ @abc.abstractmethod
+ def invocation_metadata(self):
+ """Accesses the metadata from the invocation-side of the RPC.
Returns:
The invocation :term:`metadata`.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def peer(self):
- """Identifies the peer that invoked the RPC being serviced.
+ @abc.abstractmethod
+ def peer(self):
+ """Identifies the peer that invoked the RPC being serviced.
Returns:
A string identifying the peer that invoked the RPC being serviced.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def send_initial_metadata(self, initial_metadata):
- """Sends the initial metadata value to the invocation-side of the RPC.
+ @abc.abstractmethod
+ def send_initial_metadata(self, initial_metadata):
+ """Sends the initial metadata value to the invocation-side of the RPC.
This method need not be called by method implementations if they have no
service-side initial metadata to transmit.
@@ -746,11 +763,11 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
Args:
initial_metadata: The initial :term:`metadata`.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def set_trailing_metadata(self, trailing_metadata):
- """Accepts the trailing metadata value of the RPC.
+ @abc.abstractmethod
+ def set_trailing_metadata(self, trailing_metadata):
+ """Accepts the trailing metadata value of the RPC.
This method need not be called by method implementations if they have no
service-side trailing metadata to transmit.
@@ -758,11 +775,11 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
Args:
trailing_metadata: The trailing :term:`metadata`.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def set_code(self, code):
- """Accepts the status code of the RPC.
+ @abc.abstractmethod
+ def set_code(self, code):
+ """Accepts the status code of the RPC.
This method need not be called by method implementations if they wish the
gRPC runtime to determine the status code of the RPC.
@@ -771,11 +788,11 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
code: A StatusCode value to be transmitted to the invocation side of the
RPC as the status code of the RPC.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def set_details(self, details):
- """Accepts the service-side details of the RPC.
+ @abc.abstractmethod
+ def set_details(self, details):
+ """Accepts the service-side details of the RPC.
This method need not be called by method implementations if they have no
details to transmit.
@@ -784,14 +801,14 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
details: A string to be transmitted to the invocation side of the RPC as
the status details of the RPC.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
##################### Service-Side Handler Interfaces ########################
class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
- """An implementation of a single RPC method.
+ """An implementation of a single RPC method.
Attributes:
request_streaming: Whether the RPC supports exactly one request message or
@@ -826,7 +843,7 @@ class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
- """Describes an RPC that has just arrived for service.
+ """Describes an RPC that has just arrived for service.
Attributes:
method: The method name of the RPC.
invocation_metadata: The :term:`metadata` from the invocation side of the RPC.
@@ -834,11 +851,11 @@ class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
- """An implementation of arbitrarily many RPC methods."""
+ """An implementation of arbitrarily many RPC methods."""
- @abc.abstractmethod
- def service(self, handler_call_details):
- """Services an RPC (or not).
+ @abc.abstractmethod
+ def service(self, handler_call_details):
+ """Services an RPC (or not).
Args:
handler_call_details: A HandlerCallDetails describing the RPC.
@@ -847,11 +864,11 @@ class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
An RpcMethodHandler with which the RPC may be serviced, or None to
indicate that this object will not be servicing the RPC.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
- """An implementation of RPC methods belonging to a service.
+ """An implementation of RPC methods belonging to a service.
A service handles RPC methods with structured names of the form
'/Service.Name/Service.MethodX', where 'Service.Name' is the value
@@ -860,25 +877,25 @@ class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
service name.
"""
- @abc.abstractmethod
- def service_name(self):
- """Returns this services name.
+ @abc.abstractmethod
+ def service_name(self):
+ """Returns this services name.
Returns:
The service name.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
############################# Server Interface ###############################
class Server(six.with_metaclass(abc.ABCMeta)):
- """Services RPCs."""
+ """Services RPCs."""
- @abc.abstractmethod
- def add_generic_rpc_handlers(self, generic_rpc_handlers):
- """Registers GenericRpcHandlers with this Server.
+ @abc.abstractmethod
+ def add_generic_rpc_handlers(self, generic_rpc_handlers):
+ """Registers GenericRpcHandlers with this Server.
This method is only safe to call before the server is started.
@@ -886,11 +903,11 @@ class Server(six.with_metaclass(abc.ABCMeta)):
generic_rpc_handlers: An iterable of GenericRpcHandlers that will be used
to service RPCs after this Server is started.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def add_insecure_port(self, address):
- """Reserves a port for insecure RPC service once this Server becomes active.
+ @abc.abstractmethod
+ def add_insecure_port(self, address):
+ """Reserves a port for insecure RPC service once this Server becomes active.
This method may only be called before calling this Server's start method is
called.
@@ -904,11 +921,11 @@ class Server(six.with_metaclass(abc.ABCMeta)):
in the passed address, but will likely be different if the port number
contained in the passed address was zero.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def add_secure_port(self, address, server_credentials):
- """Reserves a port for secure RPC service after this Server becomes active.
+ @abc.abstractmethod
+ def add_secure_port(self, address, server_credentials):
+ """Reserves a port for secure RPC service after this Server becomes active.
This method may only be called before calling this Server's start method is
called.
@@ -923,20 +940,20 @@ class Server(six.with_metaclass(abc.ABCMeta)):
in the passed address, but will likely be different if the port number
contained in the passed address was zero.
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def start(self):
- """Starts this Server's service of RPCs.
+ @abc.abstractmethod
+ def start(self):
+ """Starts this Server's service of RPCs.
This method may only be called while the server is not serving RPCs (i.e. it
is not idempotent).
"""
- raise NotImplementedError()
+ raise NotImplementedError()
- @abc.abstractmethod
- def stop(self, grace):
- """Stops this Server's service of RPCs.
+ @abc.abstractmethod
+ def stop(self, grace):
+ """Stops this Server's service of RPCs.
All calls to this method immediately stop service of new RPCs. When existing
RPCs are aborted is controlled by the grace period parameter passed to this
@@ -967,15 +984,16 @@ class Server(six.with_metaclass(abc.ABCMeta)):
at the time it was stopped or if all RPCs that it had underway completed
very early in the grace period).
"""
- raise NotImplementedError()
+ raise NotImplementedError()
################################# Functions ################################
-def unary_unary_rpc_method_handler(
- behavior, request_deserializer=None, response_serializer=None):
- """Creates an RpcMethodHandler for a unary-unary RPC method.
+def unary_unary_rpc_method_handler(behavior,
+ request_deserializer=None,
+ response_serializer=None):
+ """Creates an RpcMethodHandler for a unary-unary RPC method.
Args:
behavior: The implementation of an RPC method as a callable behavior taking
@@ -987,15 +1005,16 @@ def unary_unary_rpc_method_handler(
An RpcMethodHandler for a unary-unary RPC method constructed from the given
parameters.
"""
- from grpc import _utilities
- return _utilities.RpcMethodHandler(
- False, False, request_deserializer, response_serializer, behavior, None,
- None, None)
+ from grpc import _utilities
+ return _utilities.RpcMethodHandler(False, False, request_deserializer,
+ response_serializer, behavior, None,
+ None, None)
-def unary_stream_rpc_method_handler(
- behavior, request_deserializer=None, response_serializer=None):
- """Creates an RpcMethodHandler for a unary-stream RPC method.
+def unary_stream_rpc_method_handler(behavior,
+ request_deserializer=None,
+ response_serializer=None):
+ """Creates an RpcMethodHandler for a unary-stream RPC method.
Args:
behavior: The implementation of an RPC method as a callable behavior taking
@@ -1007,15 +1026,16 @@ def unary_stream_rpc_method_handler(
An RpcMethodHandler for a unary-stream RPC method constructed from the
given parameters.
"""
- from grpc import _utilities
- return _utilities.RpcMethodHandler(
- False, True, request_deserializer, response_serializer, None, behavior,
- None, None)
+ from grpc import _utilities
+ return _utilities.RpcMethodHandler(False, True, request_deserializer,
+ response_serializer, None, behavior,
+ None, None)
-def stream_unary_rpc_method_handler(
- behavior, request_deserializer=None, response_serializer=None):
- """Creates an RpcMethodHandler for a stream-unary RPC method.
+def stream_unary_rpc_method_handler(behavior,
+ request_deserializer=None,
+ response_serializer=None):
+ """Creates an RpcMethodHandler for a stream-unary RPC method.
Args:
behavior: The implementation of an RPC method as a callable behavior taking
@@ -1027,15 +1047,16 @@ def stream_unary_rpc_method_handler(
An RpcMethodHandler for a stream-unary RPC method constructed from the
given parameters.
"""
- from grpc import _utilities
- return _utilities.RpcMethodHandler(
- True, False, request_deserializer, response_serializer, None, None,
- behavior, None)
+ from grpc import _utilities
+ return _utilities.RpcMethodHandler(True, False, request_deserializer,
+ response_serializer, None, None,
+ behavior, None)
-def stream_stream_rpc_method_handler(
- behavior, request_deserializer=None, response_serializer=None):
- """Creates an RpcMethodHandler for a stream-stream RPC method.
+def stream_stream_rpc_method_handler(behavior,
+ request_deserializer=None,
+ response_serializer=None):
+ """Creates an RpcMethodHandler for a stream-stream RPC method.
Args:
behavior: The implementation of an RPC method as a callable behavior taking
@@ -1048,14 +1069,14 @@ def stream_stream_rpc_method_handler(
An RpcMethodHandler for a stream-stream RPC method constructed from the
given parameters.
"""
- from grpc import _utilities
- return _utilities.RpcMethodHandler(
- True, True, request_deserializer, response_serializer, None, None, None,
- behavior)
+ from grpc import _utilities
+ return _utilities.RpcMethodHandler(True, True, request_deserializer,
+ response_serializer, None, None, None,
+ behavior)
def method_handlers_generic_handler(service, method_handlers):
- """Creates a grpc.GenericRpcHandler from RpcMethodHandlers.
+ """Creates a grpc.GenericRpcHandler from RpcMethodHandlers.
Args:
service: A service name to be used for the given method handlers.
@@ -1065,13 +1086,14 @@ def method_handlers_generic_handler(service, method_handlers):
Returns:
A GenericRpcHandler constructed from the given parameters.
"""
- from grpc import _utilities
- return _utilities.DictionaryGenericHandler(service, method_handlers)
+ from grpc import _utilities
+ return _utilities.DictionaryGenericHandler(service, method_handlers)
-def ssl_channel_credentials(
- root_certificates=None, private_key=None, certificate_chain=None):
- """Creates a ChannelCredentials for use with an SSL-enabled Channel.
+def ssl_channel_credentials(root_certificates=None,
+ private_key=None,
+ certificate_chain=None):
+ """Creates a ChannelCredentials for use with an SSL-enabled Channel.
Args:
root_certificates: The PEM-encoded root certificates or unset to ask for
@@ -1084,16 +1106,16 @@ def ssl_channel_credentials(
Returns:
A ChannelCredentials for use with an SSL-enabled Channel.
"""
- if private_key is not None or certificate_chain is not None:
- pair = _cygrpc.SslPemKeyCertPair(private_key, certificate_chain)
- else:
- pair = None
- return ChannelCredentials(
- _cygrpc.channel_credentials_ssl(root_certificates, pair))
+ if private_key is not None or certificate_chain is not None:
+ pair = _cygrpc.SslPemKeyCertPair(private_key, certificate_chain)
+ else:
+ pair = None
+ return ChannelCredentials(
+ _cygrpc.channel_credentials_ssl(root_certificates, pair))
def metadata_call_credentials(metadata_plugin, name=None):
- """Construct CallCredentials from an AuthMetadataPlugin.
+ """Construct CallCredentials from an AuthMetadataPlugin.
Args:
metadata_plugin: An AuthMetadataPlugin to use as the authentication behavior
@@ -1103,21 +1125,21 @@ def metadata_call_credentials(metadata_plugin, name=None):
Returns:
A CallCredentials.
"""
- from grpc import _plugin_wrapping
- if name is None:
- try:
- effective_name = metadata_plugin.__name__
- except AttributeError:
- effective_name = metadata_plugin.__class__.__name__
- else:
- effective_name = name
- return CallCredentials(
- _plugin_wrapping.call_credentials_metadata_plugin(
- metadata_plugin, effective_name))
+ from grpc import _plugin_wrapping
+ if name is None:
+ try:
+ effective_name = metadata_plugin.__name__
+ except AttributeError:
+ effective_name = metadata_plugin.__class__.__name__
+ else:
+ effective_name = name
+ return CallCredentials(
+ _plugin_wrapping.call_credentials_metadata_plugin(metadata_plugin,
+ effective_name))
def access_token_call_credentials(access_token):
- """Construct CallCredentials from an access token.
+ """Construct CallCredentials from an access token.
Args:
access_token: A string to place directly in the http request
@@ -1126,13 +1148,13 @@ def access_token_call_credentials(access_token):
Returns:
A CallCredentials.
"""
- from grpc import _auth
- return metadata_call_credentials(
- _auth.AccessTokenCallCredentials(access_token))
+ from grpc import _auth
+ return metadata_call_credentials(
+ _auth.AccessTokenCallCredentials(access_token))
def composite_call_credentials(*call_credentials):
- """Compose multiple CallCredentials to make a new CallCredentials.
+ """Compose multiple CallCredentials to make a new CallCredentials.
Args:
*call_credentials: At least two CallCredentials objects.
@@ -1140,16 +1162,16 @@ def composite_call_credentials(*call_credentials):
Returns:
A CallCredentials object composed of the given CallCredentials objects.
"""
- from grpc import _credential_composition
- cygrpc_call_credentials = tuple(
- single_call_credentials._credentials
- for single_call_credentials in call_credentials)
- return CallCredentials(
- _credential_composition.call(cygrpc_call_credentials))
+ from grpc import _credential_composition
+ cygrpc_call_credentials = tuple(
+ single_call_credentials._credentials
+ for single_call_credentials in call_credentials)
+ return CallCredentials(
+ _credential_composition.call(cygrpc_call_credentials))
def composite_channel_credentials(channel_credentials, *call_credentials):
- """Compose a ChannelCredentials and one or more CallCredentials objects.
+ """Compose a ChannelCredentials and one or more CallCredentials objects.
Args:
channel_credentials: A ChannelCredentials.
@@ -1159,19 +1181,19 @@ def composite_channel_credentials(channel_credentials, *call_credentials):
A ChannelCredentials composed of the given ChannelCredentials and
CallCredentials objects.
"""
- from grpc import _credential_composition
- cygrpc_call_credentials = tuple(
- single_call_credentials._credentials
- for single_call_credentials in call_credentials)
- return ChannelCredentials(
- _credential_composition.channel(
- channel_credentials._credentials, cygrpc_call_credentials))
+ from grpc import _credential_composition
+ cygrpc_call_credentials = tuple(
+ single_call_credentials._credentials
+ for single_call_credentials in call_credentials)
+ return ChannelCredentials(
+ _credential_composition.channel(channel_credentials._credentials,
+ cygrpc_call_credentials))
-def ssl_server_credentials(
- private_key_certificate_chain_pairs, root_certificates=None,
- require_client_auth=False):
- """Creates a ServerCredentials for use with an SSL-enabled Server.
+def ssl_server_credentials(private_key_certificate_chain_pairs,
+ root_certificates=None,
+ require_client_auth=False):
+ """Creates a ServerCredentials for use with an SSL-enabled Server.
Args:
private_key_certificate_chain_pairs: A nonempty sequence each element of
@@ -1187,23 +1209,23 @@ def ssl_server_credentials(
Returns:
A ServerCredentials for use with an SSL-enabled Server.
"""
- if len(private_key_certificate_chain_pairs) == 0:
- raise ValueError(
- 'At least one private key-certificate chain pair is required!')
- elif require_client_auth and root_certificates is None:
- raise ValueError(
- 'Illegal to require client auth without providing root certificates!')
- else:
- return ServerCredentials(
- _cygrpc.server_credentials_ssl(
- root_certificates,
- [_cygrpc.SslPemKeyCertPair(key, pem)
- for key, pem in private_key_certificate_chain_pairs],
- require_client_auth))
+ if len(private_key_certificate_chain_pairs) == 0:
+ raise ValueError(
+ 'At least one private key-certificate chain pair is required!')
+ elif require_client_auth and root_certificates is None:
+ raise ValueError(
+ 'Illegal to require client auth without providing root certificates!'
+ )
+ else:
+ return ServerCredentials(
+ _cygrpc.server_credentials_ssl(root_certificates, [
+ _cygrpc.SslPemKeyCertPair(key, pem)
+ for key, pem in private_key_certificate_chain_pairs
+ ], require_client_auth))
def channel_ready_future(channel):
- """Creates a Future tracking when a Channel is ready.
+ """Creates a Future tracking when a Channel is ready.
Cancelling the returned Future does not tell the given Channel to abandon
attempts it may have been making to connect; cancelling merely deactivates the
@@ -1216,12 +1238,12 @@ def channel_ready_future(channel):
A Future that matures when the given Channel has connectivity
ChannelConnectivity.READY.
"""
- from grpc import _utilities
- return _utilities.channel_ready_future(channel)
+ from grpc import _utilities
+ return _utilities.channel_ready_future(channel)
def insecure_channel(target, options=None):
- """Creates an insecure Channel to a server.
+ """Creates an insecure Channel to a server.
Args:
target: The target to which to connect.
@@ -1231,12 +1253,12 @@ def insecure_channel(target, options=None):
Returns:
A Channel to the target through which RPCs may be conducted.
"""
- from grpc import _channel
- return _channel.Channel(target, () if options is None else options, None)
+ from grpc import _channel
+ return _channel.Channel(target, () if options is None else options, None)
def secure_channel(target, credentials, options=None):
- """Creates a secure Channel to a server.
+ """Creates a secure Channel to a server.
Args:
target: The target to which to connect.
@@ -1247,13 +1269,13 @@ def secure_channel(target, credentials, options=None):
Returns:
A Channel to the target through which RPCs may be conducted.
"""
- from grpc import _channel
- return _channel.Channel(target, () if options is None else options,
- credentials._credentials)
+ from grpc import _channel
+ return _channel.Channel(target, () if options is None else options,
+ credentials._credentials)
def server(thread_pool, handlers=None, options=None):
- """Creates a Server with which RPCs can be serviced.
+ """Creates a Server with which RPCs can be serviced.
Args:
thread_pool: A futures.ThreadPoolExecutor to be used by the returned Server
@@ -1269,14 +1291,13 @@ def server(thread_pool, handlers=None, options=None):
Returns:
A Server with which RPCs can be serviced.
"""
- from grpc import _server
- return _server.Server(thread_pool, () if handlers is None else handlers,
- () if options is None else options)
+ from grpc import _server
+ return _server.Server(thread_pool, () if handlers is None else handlers, ()
+ if options is None else options)
################################### __all__ #################################
-
__all__ = (
'FutureTimeoutError',
'FutureCancelledError',
@@ -1317,26 +1338,23 @@ __all__ = (
'channel_ready_future',
'insecure_channel',
'secure_channel',
- 'server',
-)
-
+ 'server',)
############################### Extension Shims ################################
-
# Here to maintain backwards compatibility; avoid using these in new code!
try:
- import grpc_tools
- sys.modules.update({'grpc.tools': grpc_tools})
+ import grpc_tools
+ sys.modules.update({'grpc.tools': grpc_tools})
except ImportError:
- pass
+ pass
try:
- import grpc_health
- sys.modules.update({'grpc.health': grpc_health})
+ import grpc_health
+ sys.modules.update({'grpc.health': grpc_health})
except ImportError:
- pass
+ pass
try:
- import grpc_reflection
- sys.modules.update({'grpc.reflection': grpc_reflection})
+ import grpc_reflection
+ sys.modules.update({'grpc.reflection': grpc_reflection})
except ImportError:
- pass
+ pass