1 # Copyright 2015-2016 gRPC authors.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 """gRPC's Python API."""
23 from grpc._cython import cygrpc as _cygrpc
24 from grpc import _compression
26 logging.getLogger(__name__).addHandler(logging.NullHandler())
29 from grpc._grpcio_metadata import __version__
33 ############################## Future Interface ###############################
36 class FutureTimeoutError(Exception):
37 """Indicates that a method call on a Future timed out."""
40 class FutureCancelledError(Exception):
41 """Indicates that the computation underlying a Future was cancelled."""
44 class Future(six.with_metaclass(abc.ABCMeta)):
45 """A representation of a computation in another control flow.
47 Computations represented by a Future may be yet to be begun,
48 may be ongoing, or may have already completed.
53 """Attempts to cancel the computation.
55 This method does not block.
59 Returns True if the computation was canceled.
61 Returns False under all other circumstances, for example:
63 1. computation has begun and could not be canceled.
64 2. computation has finished
65 3. computation is scheduled for execution and it is impossible
66 to determine its state without blocking.
68 raise NotImplementedError()
72 """Describes whether the computation was cancelled.
74 This method does not block.
78 Returns True if the computation was cancelled before its result became
81 Returns False under all other circumstances, for example:
83 1. computation was not cancelled.
84 2. computation's result is available.
86 raise NotImplementedError()
90 """Describes whether the computation is taking place.
92 This method does not block.
95 Returns True if the computation is scheduled for execution or
98 Returns False if the computation already executed or was cancelled.
100 raise NotImplementedError()
104 """Describes whether the computation has taken place.
106 This method does not block.
110 Returns True if the computation already executed or was cancelled.
111 Returns False if the computation is scheduled for execution or
113 This is exactly opposite of the running() method's result.
115 raise NotImplementedError()
118 def result(self, timeout=None):
119 """Returns the result of the computation or raises its exception.
121 This method may return immediately or may block.
124 timeout: The length of time in seconds to wait for the computation to
125 finish or be cancelled. If None, the call will block until the
126 computations's termination.
129 The return value of the computation.
132 FutureTimeoutError: If a timeout value is passed and the computation
133 does not terminate within the allotted time.
134 FutureCancelledError: If the computation was cancelled.
135 Exception: If the computation raised an exception, this call will
136 raise the same exception.
138 raise NotImplementedError()
141 def exception(self, timeout=None):
142 """Return the exception raised by the computation.
144 This method may return immediately or may block.
147 timeout: The length of time in seconds to wait for the computation to
148 terminate or be cancelled. If None, the call will block until the
149 computations's termination.
152 The exception raised by the computation, or None if the computation
153 did not raise an exception.
156 FutureTimeoutError: If a timeout value is passed and the computation
157 does not terminate within the allotted time.
158 FutureCancelledError: If the computation was cancelled.
160 raise NotImplementedError()
163 def traceback(self, timeout=None):
164 """Access the traceback of the exception raised by the computation.
166 This method may return immediately or may block.
169 timeout: The length of time in seconds to wait for the computation
170 to terminate or be cancelled. If None, the call will block until
171 the computation's termination.
174 The traceback of the exception raised by the computation, or None
175 if the computation did not raise an exception.
178 FutureTimeoutError: If a timeout value is passed and the computation
179 does not terminate within the allotted time.
180 FutureCancelledError: If the computation was cancelled.
182 raise NotImplementedError()
185 def add_done_callback(self, fn):
186 """Adds a function to be called at completion of the computation.
188 The callback will be passed this Future object describing the outcome
189 of the computation. Callbacks will be invoked after the future is
190 terimated, whether successfully or not.
192 If the computation has already completed, the callback will be called
196 fn: A callable taking this Future object as its single parameter.
198 raise NotImplementedError()
201 ################################ gRPC Enums ##################################
205 class ChannelConnectivity(enum.Enum):
206 """Mirrors grpc_connectivity_state in the gRPC Core.
209 IDLE: The channel is idle.
210 CONNECTING: The channel is connecting.
211 READY: The channel is ready to conduct RPCs.
212 TRANSIENT_FAILURE: The channel has seen a failure from which it expects
214 SHUTDOWN: The channel has seen a failure from which it cannot recover.
216 IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
217 CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
218 READY = (_cygrpc.ConnectivityState.ready, 'ready')
219 TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure,
221 SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
225 class StatusCode(enum.Enum):
226 """Mirrors grpc_status_code in the gRPC Core.
229 OK: Not an error; returned on success
230 CANCELLED: The operation was cancelled (typically by the caller).
231 UNKNOWN: Unknown error.
232 INVALID_ARGUMENT: Client specified an invalid argument.
233 DEADLINE_EXCEEDED: Deadline expired before operation could complete.
234 NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
235 ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
237 PERMISSION_DENIED: The caller does not have permission to execute the specified
239 UNAUTHENTICATED: The request does not have valid authentication credentials for the
241 RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
242 perhaps the entire file system is out of space.
243 FAILED_PRECONDITION: Operation was rejected because the system is not in a state
244 required for the operation's execution.
245 ABORTED: The operation was aborted, typically due to a concurrency issue
246 like sequencer check failures, transaction aborts, etc.
247 UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
248 INTERNAL: Internal errors. Means some invariants expected by underlying
249 system has been broken.
250 UNAVAILABLE: The service is currently unavailable.
251 DATA_LOSS: Unrecoverable data loss or corruption.
253 OK = (_cygrpc.StatusCode.ok, 'ok')
254 CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
255 UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
256 INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument')
257 DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded,
259 NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
260 ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
261 PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied,
263 RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted,
264 'resource exhausted')
265 FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition,
266 'failed precondition')
267 ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
268 OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
269 UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
270 INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
271 UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
272 DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
273 UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
276 ############################# gRPC Status ################################
279 class Status(six.with_metaclass(abc.ABCMeta)):
280 """Describes the status of an RPC.
282 This is an EXPERIMENTAL API.
285 code: A StatusCode object to be sent to the client.
286 details: A UTF-8-encodable string to be sent to the client upon
287 termination of the RPC.
288 trailing_metadata: The trailing :term:`metadata` in the RPC.
292 ############################# gRPC Exceptions ################################
295 class RpcError(Exception):
296 """Raised by the gRPC library to indicate non-OK-status RPC termination."""
299 ############################## Shared Context ################################
302 class RpcContext(six.with_metaclass(abc.ABCMeta)):
303 """Provides RPC-related information and action."""
307 """Describes whether the RPC is active or has terminated.
311 True if RPC is active, False otherwise.
313 raise NotImplementedError()
316 def time_remaining(self):
317 """Describes the length of allowed time remaining for the RPC.
320 A nonnegative float indicating the length of allowed time in seconds
321 remaining for the RPC to complete before it is considered to have
322 timed out, or None if no deadline was specified for the RPC.
324 raise NotImplementedError()
330 Idempotent and has no effect if the RPC has already terminated.
332 raise NotImplementedError()
335 def add_callback(self, callback):
336 """Registers a callback to be called on RPC termination.
339 callback: A no-parameter callable to be called on RPC termination.
343 True if the callback was added and will be called later; False if
344 the callback was not added and will not be called (because the RPC
345 already terminated or some other reason).
347 raise NotImplementedError()
350 ######################### Invocation-Side Context ############################
353 class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
354 """Invocation-side utility object for an RPC."""
357 def initial_metadata(self):
358 """Accesses the initial metadata sent by the server.
360 This method blocks until the value is available.
363 The initial :term:`metadata`.
365 raise NotImplementedError()
368 def trailing_metadata(self):
369 """Accesses the trailing metadata sent by the server.
371 This method blocks until the value is available.
374 The trailing :term:`metadata`.
376 raise NotImplementedError()
380 """Accesses the status code sent by the server.
382 This method blocks until the value is available.
385 The StatusCode value for the RPC.
387 raise NotImplementedError()
391 """Accesses the details sent by the server.
393 This method blocks until the value is available.
396 The details string of the RPC.
398 raise NotImplementedError()
401 ############## Invocation-Side Interceptor Interfaces & Classes ##############
404 class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
405 """Describes an RPC to be invoked.
407 This is an EXPERIMENTAL API.
410 method: The method name of the RPC.
411 timeout: An optional duration of time in seconds to allow for the RPC.
412 metadata: Optional :term:`metadata` to be transmitted to
413 the service-side of the RPC.
414 credentials: An optional CallCredentials for the RPC.
415 wait_for_ready: This is an EXPERIMENTAL argument. An optional flag t
416 enable wait for ready mechanism.
417 compression: An element of grpc.compression, e.g.
418 grpc.compression.Gzip. This is an EXPERIMENTAL option.
422 class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
423 """Affords intercepting unary-unary invocations.
425 This is an EXPERIMENTAL API.
429 def intercept_unary_unary(self, continuation, client_call_details, request):
430 """Intercepts a unary-unary invocation asynchronously.
433 continuation: A function that proceeds with the invocation by
434 executing the next interceptor in chain or invoking the
435 actual RPC on the underlying Channel. It is the interceptor's
436 responsibility to call it if it decides to move the RPC forward.
437 The interceptor can use
438 `response_future = continuation(client_call_details, request)`
439 to continue with the RPC. `continuation` returns an object that is
440 both a Call for the RPC and a Future. In the event of RPC
441 completion, the return Call-Future's result value will be
442 the response message of the RPC. Should the event terminate
443 with non-OK status, the returned Call-Future's exception value
445 client_call_details: A ClientCallDetails object describing the
447 request: The request value for the RPC.
450 An object that is both a Call for the RPC and a Future.
451 In the event of RPC completion, the return Call-Future's
452 result value will be the response message of the RPC.
453 Should the event terminate with non-OK status, the returned
454 Call-Future's exception value will be an RpcError.
456 raise NotImplementedError()
459 class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
460 """Affords intercepting unary-stream invocations.
462 This is an EXPERIMENTAL API.
466 def intercept_unary_stream(self, continuation, client_call_details,
468 """Intercepts a unary-stream invocation.
471 continuation: A function that proceeds with the invocation by
472 executing the next interceptor in chain or invoking the
473 actual RPC on the underlying Channel. It is the interceptor's
474 responsibility to call it if it decides to move the RPC forward.
475 The interceptor can use
476 `response_iterator = continuation(client_call_details, request)`
477 to continue with the RPC. `continuation` returns an object that is
478 both a Call for the RPC and an iterator for response values.
479 Drawing response values from the returned Call-iterator may
480 raise RpcError indicating termination of the RPC with non-OK
482 client_call_details: A ClientCallDetails object describing the
484 request: The request value for the RPC.
487 An object that is both a Call for the RPC and an iterator of
488 response values. Drawing response values from the returned
489 Call-iterator may raise RpcError indicating termination of
490 the RPC with non-OK status.
492 raise NotImplementedError()
495 class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
496 """Affords intercepting stream-unary invocations.
498 This is an EXPERIMENTAL API.
502 def intercept_stream_unary(self, continuation, client_call_details,
504 """Intercepts a stream-unary invocation asynchronously.
507 continuation: A function that proceeds with the invocation by
508 executing the next interceptor in chain or invoking the
509 actual RPC on the underlying Channel. It is the interceptor's
510 responsibility to call it if it decides to move the RPC forward.
511 The interceptor can use
512 `response_future = continuation(client_call_details, request_iterator)`
513 to continue with the RPC. `continuation` returns an object that is
514 both a Call for the RPC and a Future. In the event of RPC completion,
515 the return Call-Future's result value will be the response message
516 of the RPC. Should the event terminate with non-OK status, the
517 returned Call-Future's exception value will be an RpcError.
518 client_call_details: A ClientCallDetails object describing the
520 request_iterator: An iterator that yields request values for the RPC.
523 An object that is both a Call for the RPC and a Future.
524 In the event of RPC completion, the return Call-Future's
525 result value will be the response message of the RPC.
526 Should the event terminate with non-OK status, the returned
527 Call-Future's exception value will be an RpcError.
529 raise NotImplementedError()
532 class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
533 """Affords intercepting stream-stream invocations.
535 This is an EXPERIMENTAL API.
539 def intercept_stream_stream(self, continuation, client_call_details,
541 """Intercepts a stream-stream invocation.
544 continuation: A function that proceeds with the invocation by
545 executing the next interceptor in chain or invoking the
546 actual RPC on the underlying Channel. It is the interceptor's
547 responsibility to call it if it decides to move the RPC forward.
548 The interceptor can use
549 `response_iterator = continuation(client_call_details, request_iterator)`
550 to continue with the RPC. `continuation` returns an object that is
551 both a Call for the RPC and an iterator for response values.
552 Drawing response values from the returned Call-iterator may
553 raise RpcError indicating termination of the RPC with non-OK
555 client_call_details: A ClientCallDetails object describing the
557 request_iterator: An iterator that yields request values for the RPC.
560 An object that is both a Call for the RPC and an iterator of
561 response values. Drawing response values from the returned
562 Call-iterator may raise RpcError indicating termination of
563 the RPC with non-OK status.
565 raise NotImplementedError()
568 ############ Authentication & Authorization Interfaces & Classes #############
571 class ChannelCredentials(object):
572 """An encapsulation of the data required to create a secure Channel.
574 This class has no supported interface - it exists to define the type of its
575 instances and its instances exist to be passed to other functions. For
576 example, ssl_channel_credentials returns an instance of this class and
577 secure_channel requires an instance of this class.
580 def __init__(self, credentials):
581 self._credentials = credentials
584 class CallCredentials(object):
585 """An encapsulation of the data required to assert an identity over a call.
587 A CallCredentials has to be used with secure Channel, otherwise the
588 metadata will not be transmitted to the server.
590 A CallCredentials may be composed with ChannelCredentials to always assert
591 identity for every call over that Channel.
593 This class has no supported interface - it exists to define the type of its
594 instances and its instances exist to be passed to other functions.
597 def __init__(self, credentials):
598 self._credentials = credentials
601 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
602 """Provides information to call credentials metadata plugins.
605 service_url: A string URL of the service being called into.
606 method_name: A string of the fully qualified method name being called.
610 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
611 """Callback object received by a metadata plugin."""
613 def __call__(self, metadata, error):
614 """Passes to the gRPC runtime authentication metadata for an RPC.
617 metadata: The :term:`metadata` used to construct the CallCredentials.
618 error: An Exception to indicate error or None to indicate success.
620 raise NotImplementedError()
623 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
624 """A specification for custom authentication."""
626 def __call__(self, context, callback):
627 """Implements authentication by passing metadata to a callback.
629 Implementations of this method must not block.
632 context: An AuthMetadataContext providing information on the RPC that
633 the plugin is being called to authenticate.
634 callback: An AuthMetadataPluginCallback to be invoked either
635 synchronously or asynchronously.
637 raise NotImplementedError()
640 class ServerCredentials(object):
641 """An encapsulation of the data required to open a secure port on a Server.
643 This class has no supported interface - it exists to define the type of its
644 instances and its instances exist to be passed to other functions.
647 def __init__(self, credentials):
648 self._credentials = credentials
651 class ServerCertificateConfiguration(object):
652 """A certificate configuration for use with an SSL-enabled Server.
654 Instances of this class can be returned in the certificate configuration
657 This class has no supported interface -- it exists to define the
658 type of its instances and its instances exist to be passed to
662 def __init__(self, certificate_configuration):
663 self._certificate_configuration = certificate_configuration
666 ######################## Multi-Callable Interfaces ###########################
669 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
670 """Affords invoking a unary-unary RPC from client-side."""
680 """Synchronously invokes the underlying RPC.
683 request: The request value for the RPC.
684 timeout: An optional duration of time in seconds to allow
686 metadata: Optional :term:`metadata` to be transmitted to the
687 service-side of the RPC.
688 credentials: An optional CallCredentials for the RPC. Only valid for
690 wait_for_ready: This is an EXPERIMENTAL argument. An optional
691 flag to enable wait for ready mechanism
692 compression: An element of grpc.compression, e.g.
693 grpc.compression.Gzip. This is an EXPERIMENTAL option.
696 The response value for the RPC.
699 RpcError: Indicating that the RPC terminated with non-OK status. The
700 raised RpcError will also be a Call for the RPC affording the RPC's
701 metadata, status code, and details.
703 raise NotImplementedError()
713 """Synchronously invokes the underlying RPC.
716 request: The request value for the RPC.
717 timeout: An optional durating of time in seconds to allow for
719 metadata: Optional :term:`metadata` to be transmitted to the
720 service-side of the RPC.
721 credentials: An optional CallCredentials for the RPC. Only valid for
723 wait_for_ready: This is an EXPERIMENTAL argument. An optional
724 flag to enable wait for ready mechanism
725 compression: An element of grpc.compression, e.g.
726 grpc.compression.Gzip. This is an EXPERIMENTAL option.
729 The response value for the RPC and a Call value for the RPC.
732 RpcError: Indicating that the RPC terminated with non-OK status. The
733 raised RpcError will also be a Call for the RPC affording the RPC's
734 metadata, status code, and details.
736 raise NotImplementedError()
746 """Asynchronously invokes the underlying RPC.
749 request: The request value for the RPC.
750 timeout: An optional duration of time in seconds to allow for
752 metadata: Optional :term:`metadata` to be transmitted to the
753 service-side of the RPC.
754 credentials: An optional CallCredentials for the RPC. Only valid for
756 wait_for_ready: This is an EXPERIMENTAL argument. An optional
757 flag to enable wait for ready mechanism
758 compression: An element of grpc.compression, e.g.
759 grpc.compression.Gzip. This is an EXPERIMENTAL option.
762 An object that is both a Call for the RPC and a Future.
763 In the event of RPC completion, the return Call-Future's result
764 value will be the response message of the RPC.
765 Should the event terminate with non-OK status,
766 the returned Call-Future's exception value will be an RpcError.
768 raise NotImplementedError()
771 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
772 """Affords invoking a unary-stream RPC from client-side."""
782 """Invokes the underlying RPC.
785 request: The request value for the RPC.
786 timeout: An optional duration of time in seconds to allow for
787 the RPC. If None, the timeout is considered infinite.
788 metadata: An optional :term:`metadata` to be transmitted to the
789 service-side of the RPC.
790 credentials: An optional CallCredentials for the RPC. Only valid for
792 wait_for_ready: This is an EXPERIMENTAL argument. An optional
793 flag to enable wait for ready mechanism
794 compression: An element of grpc.compression, e.g.
795 grpc.compression.Gzip. This is an EXPERIMENTAL option.
798 An object that is both a Call for the RPC and an iterator of
799 response values. Drawing response values from the returned
800 Call-iterator may raise RpcError indicating termination of the
801 RPC with non-OK status.
803 raise NotImplementedError()
806 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
807 """Affords invoking a stream-unary RPC from client-side."""
817 """Synchronously invokes the underlying RPC.
820 request_iterator: An iterator that yields request values for
822 timeout: An optional duration of time in seconds to allow for
823 the RPC. If None, the timeout is considered infinite.
824 metadata: Optional :term:`metadata` to be transmitted to the
825 service-side of the RPC.
826 credentials: An optional CallCredentials for the RPC. Only valid for
828 wait_for_ready: This is an EXPERIMENTAL argument. An optional
829 flag to enable wait for ready mechanism
830 compression: An element of grpc.compression, e.g.
831 grpc.compression.Gzip. This is an EXPERIMENTAL option.
834 The response value for the RPC.
837 RpcError: Indicating that the RPC terminated with non-OK status. The
838 raised RpcError will also implement grpc.Call, affording methods
839 such as metadata, code, and details.
841 raise NotImplementedError()
851 """Synchronously invokes the underlying RPC on the client.
854 request_iterator: An iterator that yields request values for
856 timeout: An optional duration of time in seconds to allow for
857 the RPC. If None, the timeout is considered infinite.
858 metadata: Optional :term:`metadata` to be transmitted to the
859 service-side of the RPC.
860 credentials: An optional CallCredentials for the RPC. Only valid for
862 wait_for_ready: This is an EXPERIMENTAL argument. An optional
863 flag to enable wait for ready mechanism
864 compression: An element of grpc.compression, e.g.
865 grpc.compression.Gzip. This is an EXPERIMENTAL option.
868 The response value for the RPC and a Call object for the RPC.
871 RpcError: Indicating that the RPC terminated with non-OK status. The
872 raised RpcError will also be a Call for the RPC affording the RPC's
873 metadata, status code, and details.
875 raise NotImplementedError()
885 """Asynchronously invokes the underlying RPC on the client.
888 request_iterator: An iterator that yields request values for the RPC.
889 timeout: An optional duration of time in seconds to allow for
890 the RPC. If None, the timeout is considered infinite.
891 metadata: Optional :term:`metadata` to be transmitted to the
892 service-side of the RPC.
893 credentials: An optional CallCredentials for the RPC. Only valid for
895 wait_for_ready: This is an EXPERIMENTAL argument. An optional
896 flag to enable wait for ready mechanism
897 compression: An element of grpc.compression, e.g.
898 grpc.compression.Gzip. This is an EXPERIMENTAL option.
901 An object that is both a Call for the RPC and a Future.
902 In the event of RPC completion, the return Call-Future's result value
903 will be the response message of the RPC. Should the event terminate
904 with non-OK status, the returned Call-Future's exception value will
907 raise NotImplementedError()
910 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
911 """Affords invoking a stream-stream RPC on client-side."""
921 """Invokes the underlying RPC on the client.
924 request_iterator: An iterator that yields request values for the RPC.
925 timeout: An optional duration of time in seconds to allow for
926 the RPC. If not specified, the timeout is considered infinite.
927 metadata: Optional :term:`metadata` to be transmitted to the
928 service-side of the RPC.
929 credentials: An optional CallCredentials for the RPC. Only valid for
931 wait_for_ready: This is an EXPERIMENTAL argument. An optional
932 flag to enable wait for ready mechanism
933 compression: An element of grpc.compression, e.g.
934 grpc.compression.Gzip. This is an EXPERIMENTAL option.
937 An object that is both a Call for the RPC and an iterator of
938 response values. Drawing response values from the returned
939 Call-iterator may raise RpcError indicating termination of the
940 RPC with non-OK status.
942 raise NotImplementedError()
945 ############################# Channel Interface ##############################
948 class Channel(six.with_metaclass(abc.ABCMeta)):
949 """Affords RPC invocation via generic methods on client-side.
951 Channel objects implement the Context Manager type, although they need not
952 support being entered and exited multiple times.
956 def subscribe(self, callback, try_to_connect=False):
957 """Subscribe to this Channel's connectivity state machine.
959 A Channel may be in any of the states described by ChannelConnectivity.
960 This method allows application to monitor the state transitions.
961 The typical use case is to debug or gain better visibility into gRPC
965 callback: A callable to be invoked with ChannelConnectivity argument.
966 ChannelConnectivity describes current state of the channel.
967 The callable will be invoked immediately upon subscription
968 and again for every change to ChannelConnectivity until it
969 is unsubscribed or this Channel object goes out of scope.
970 try_to_connect: A boolean indicating whether or not this Channel
971 should attempt to connect immediately. If set to False, gRPC
972 runtime decides when to connect.
974 raise NotImplementedError()
977 def unsubscribe(self, callback):
978 """Unsubscribes a subscribed callback from this Channel's connectivity.
981 callback: A callable previously registered with this Channel from
982 having been passed to its "subscribe" method.
984 raise NotImplementedError()
987 def unary_unary(self,
989 request_serializer=None,
990 response_deserializer=None):
991 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
994 method: The name of the RPC method.
995 request_serializer: Optional behaviour for serializing the request
996 message. Request goes unserialized in case None is passed.
997 response_deserializer: Optional behaviour for deserializing the
998 response message. Response goes undeserialized in case None
1002 A UnaryUnaryMultiCallable value for the named unary-unary method.
1004 raise NotImplementedError()
1007 def unary_stream(self,
1009 request_serializer=None,
1010 response_deserializer=None):
1011 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1014 method: The name of the RPC method.
1015 request_serializer: Optional behaviour for serializing the request
1016 message. Request goes unserialized in case None is passed.
1017 response_deserializer: Optional behaviour for deserializing the
1018 response message. Response goes undeserialized in case None is
1022 A UnaryStreamMultiCallable value for the name unary-stream method.
1024 raise NotImplementedError()
1027 def stream_unary(self,
1029 request_serializer=None,
1030 response_deserializer=None):
1031 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1034 method: The name of the RPC method.
1035 request_serializer: Optional behaviour for serializing the request
1036 message. Request goes unserialized in case None is passed.
1037 response_deserializer: Optional behaviour for deserializing the
1038 response message. Response goes undeserialized in case None is
1042 A StreamUnaryMultiCallable value for the named stream-unary method.
1044 raise NotImplementedError()
1047 def stream_stream(self,
1049 request_serializer=None,
1050 response_deserializer=None):
1051 """Creates a StreamStreamMultiCallable for a stream-stream method.
1054 method: The name of the RPC method.
1055 request_serializer: Optional behaviour for serializing the request
1056 message. Request goes unserialized in case None is passed.
1057 response_deserializer: Optional behaviour for deserializing the
1058 response message. Response goes undeserialized in case None
1062 A StreamStreamMultiCallable value for the named stream-stream method.
1064 raise NotImplementedError()
1068 """Closes this Channel and releases all resources held by it.
1070 Closing the Channel will immediately terminate all RPCs active with the
1071 Channel and it is not valid to invoke new RPCs with the Channel.
1073 This method is idempotent.
1075 raise NotImplementedError()
1078 ########################## Service-Side Context ##############################
1081 class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1082 """A context object passed to method implementations."""
1085 def invocation_metadata(self):
1086 """Accesses the metadata from the sent by the client.
1089 The invocation :term:`metadata`.
1091 raise NotImplementedError()
1095 """Identifies the peer that invoked the RPC being serviced.
1098 A string identifying the peer that invoked the RPC being serviced.
1099 The string format is determined by gRPC runtime.
1101 raise NotImplementedError()
1104 def peer_identities(self):
1105 """Gets one or more peer identity(s).
1108 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1111 An iterable of the identities, or None if the call is not
1112 authenticated. Each identity is returned as a raw bytes type.
1114 raise NotImplementedError()
1117 def peer_identity_key(self):
1118 """The auth property used to identify the peer.
1120 For example, "x509_common_name" or "x509_subject_alternative_name" are
1121 used to identify an SSL peer.
1124 The auth property (string) that indicates the
1125 peer identity, or None if the call is not authenticated.
1127 raise NotImplementedError()
1130 def auth_context(self):
1131 """Gets the auth context for the call.
1134 A map of strings to an iterable of bytes for each auth property.
1136 raise NotImplementedError()
1138 def set_compression(self, compression):
1139 """Set the compression algorithm to be used for the entire call.
1141 This is an EXPERIMENTAL method.
1144 compression: An element of grpc.compression, e.g.
1145 grpc.compression.Gzip.
1147 raise NotImplementedError()
1150 def send_initial_metadata(self, initial_metadata):
1151 """Sends the initial metadata value to the client.
1153 This method need not be called by implementations if they have no
1154 metadata to add to what the gRPC runtime will transmit.
1157 initial_metadata: The initial :term:`metadata`.
1159 raise NotImplementedError()
1162 def set_trailing_metadata(self, trailing_metadata):
1163 """Sends the trailing metadata for the RPC.
1165 This method need not be called by implementations if they have no
1166 metadata to add to what the gRPC runtime will transmit.
1169 trailing_metadata: The trailing :term:`metadata`.
1171 raise NotImplementedError()
1174 def abort(self, code, details):
1175 """Raises an exception to terminate the RPC with a non-OK status.
1177 The code and details passed as arguments will supercede any existing
1181 code: A StatusCode object to be sent to the client.
1182 It must not be StatusCode.OK.
1183 details: A UTF-8-encodable string to be sent to the client upon
1184 termination of the RPC.
1187 Exception: An exception is always raised to signal the abortion the
1188 RPC to the gRPC runtime.
1190 raise NotImplementedError()
1193 def abort_with_status(self, status):
1194 """Raises an exception to terminate the RPC with a non-OK status.
1196 The status passed as argument will supercede any existing status code,
1197 status message and trailing metadata.
1199 This is an EXPERIMENTAL API.
1202 status: A grpc.Status object. The status code in it must not be
1206 Exception: An exception is always raised to signal the abortion the
1207 RPC to the gRPC runtime.
1209 raise NotImplementedError()
1212 def set_code(self, code):
1213 """Sets the value to be used as status code upon RPC completion.
1215 This method need not be called by method implementations if they wish
1216 the gRPC runtime to determine the status code of the RPC.
1219 code: A StatusCode object to be sent to the client.
1221 raise NotImplementedError()
1224 def set_details(self, details):
1225 """Sets the value to be used as detail string upon RPC completion.
1227 This method need not be called by method implementations if they have
1228 no details to transmit.
1231 details: A UTF-8-encodable string to be sent to the client upon
1232 termination of the RPC.
1234 raise NotImplementedError()
1236 def disable_next_message_compression(self):
1237 """Disables compression for the next response message.
1239 This is an EXPERIMENTAL method.
1241 This method will override any compression configuration set during
1242 server creation or set on the call.
1244 raise NotImplementedError()
1247 ##################### Service-Side Handler Interfaces ########################
1250 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1251 """An implementation of a single RPC method.
1254 request_streaming: Whether the RPC supports exactly one request message
1255 or any arbitrary number of request messages.
1256 response_streaming: Whether the RPC supports exactly one response message
1257 or any arbitrary number of response messages.
1258 request_deserializer: A callable behavior that accepts a byte string and
1259 returns an object suitable to be passed to this object's business
1260 logic, or None to indicate that this object's business logic should be
1261 passed the raw request bytes.
1262 response_serializer: A callable behavior that accepts an object produced
1263 by this object's business logic and returns a byte string, or None to
1264 indicate that the byte strings produced by this object's business logic
1265 should be transmitted on the wire as they are.
1266 unary_unary: This object's application-specific business logic as a
1267 callable value that takes a request value and a ServicerContext object
1268 and returns a response value. Only non-None if both request_streaming
1269 and response_streaming are False.
1270 unary_stream: This object's application-specific business logic as a
1271 callable value that takes a request value and a ServicerContext object
1272 and returns an iterator of response values. Only non-None if
1273 request_streaming is False and response_streaming is True.
1274 stream_unary: This object's application-specific business logic as a
1275 callable value that takes an iterator of request values and a
1276 ServicerContext object and returns a response value. Only non-None if
1277 request_streaming is True and response_streaming is False.
1278 stream_stream: This object's application-specific business logic as a
1279 callable value that takes an iterator of request values and a
1280 ServicerContext object and returns an iterator of response values.
1281 Only non-None if request_streaming and response_streaming are both
1286 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1287 """Describes an RPC that has just arrived for service.
1289 method: The method name of the RPC.
1290 invocation_metadata: The :term:`metadata` sent by the client.
1294 class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1295 """An implementation of arbitrarily many RPC methods."""
1298 def service(self, handler_call_details):
1299 """Returns the handler for servicing the RPC.
1302 handler_call_details: A HandlerCallDetails describing the RPC.
1305 An RpcMethodHandler with which the RPC may be serviced if the
1306 implementation chooses to service this RPC, or None otherwise.
1308 raise NotImplementedError()
1311 class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1312 """An implementation of RPC methods belonging to a service.
1314 A service handles RPC methods with structured names of the form
1315 '/Service.Name/Service.Method', where 'Service.Name' is the value
1316 returned by service_name(), and 'Service.Method' is the method
1317 name. A service can have multiple method names, but only a single
1322 def service_name(self):
1323 """Returns this service's name.
1328 raise NotImplementedError()
1331 #################### Service-Side Interceptor Interfaces #####################
1334 class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1335 """Affords intercepting incoming RPCs on the service-side.
1337 This is an EXPERIMENTAL API.
1341 def intercept_service(self, continuation, handler_call_details):
1342 """Intercepts incoming RPCs before handing them over to a handler.
1345 continuation: A function that takes a HandlerCallDetails and
1346 proceeds to invoke the next interceptor in the chain, if any,
1347 or the RPC handler lookup logic, with the call details passed
1348 as an argument, and returns an RpcMethodHandler instance if
1349 the RPC is considered serviced, or None otherwise.
1350 handler_call_details: A HandlerCallDetails describing the RPC.
1353 An RpcMethodHandler with which the RPC may be serviced if the
1354 interceptor chooses to service this RPC, or None otherwise.
1356 raise NotImplementedError()
1359 ############################# Server Interface ###############################
1362 class Server(six.with_metaclass(abc.ABCMeta)):
1363 """Services RPCs."""
1366 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1367 """Registers GenericRpcHandlers with this Server.
1369 This method is only safe to call before the server is started.
1372 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1373 used to service RPCs.
1375 raise NotImplementedError()
1378 def add_insecure_port(self, address):
1379 """Opens an insecure port for accepting RPCs.
1381 This method may only be called before starting the server.
1384 address: The address for which to open a port.
1385 if the port is 0, or not specified in the address, then gRPC runtime
1390 An integer port on which server will accept RPC requests.
1392 raise NotImplementedError()
1395 def add_secure_port(self, address, server_credentials):
1396 """Opens a secure port for accepting RPCs.
1398 This method may only be called before starting the server.
1401 address: The address for which to open a port.
1402 if the port is 0, or not specified in the address, then gRPC
1403 runtime will choose a port.
1404 server_credentials: A ServerCredentials object.
1408 An integer port on which server will accept RPC requests.
1410 raise NotImplementedError()
1414 """Starts this Server.
1416 This method may only be called once. (i.e. it is not idempotent).
1418 raise NotImplementedError()
1421 def stop(self, grace):
1422 """Stops this Server.
1424 This method immediately stop service of new RPCs in all cases.
1426 If a grace period is specified, this method returns immediately
1427 and all RPCs active at the end of the grace period are aborted.
1428 If a grace period is not specified (by passing None for `grace`),
1429 all existing RPCs are aborted immediately and this method
1430 blocks until the last RPC handler terminates.
1432 This method is idempotent and may be called at any time.
1433 Passing a smaller grace value in a subsequent call will have
1434 the effect of stopping the Server sooner (passing None will
1435 have the effect of stopping the server immediately). Passing
1436 a larger grace value in a subsequent call *will not* have the
1437 effect of stopping the server later (i.e. the most restrictive
1438 grace value is used).
1441 grace: A duration of time in seconds or None.
1444 A threading.Event that will be set when this Server has completely
1445 stopped, i.e. when running RPCs either complete or are aborted and
1446 all handlers have terminated.
1448 raise NotImplementedError()
1451 ################################# Functions ################################
1454 def unary_unary_rpc_method_handler(behavior,
1455 request_deserializer=None,
1456 response_serializer=None):
1457 """Creates an RpcMethodHandler for a unary-unary RPC method.
1460 behavior: The implementation of an RPC that accepts one request
1461 and returns one response.
1462 request_deserializer: An optional behavior for request deserialization.
1463 response_serializer: An optional behavior for response serialization.
1466 An RpcMethodHandler object that is typically used by grpc.Server.
1468 from grpc import _utilities # pylint: disable=cyclic-import
1469 return _utilities.RpcMethodHandler(False, False, request_deserializer,
1470 response_serializer, behavior, None,
1474 def unary_stream_rpc_method_handler(behavior,
1475 request_deserializer=None,
1476 response_serializer=None):
1477 """Creates an RpcMethodHandler for a unary-stream RPC method.
1480 behavior: The implementation of an RPC that accepts one request
1481 and returns an iterator of response values.
1482 request_deserializer: An optional behavior for request deserialization.
1483 response_serializer: An optional behavior for response serialization.
1486 An RpcMethodHandler object that is typically used by grpc.Server.
1488 from grpc import _utilities # pylint: disable=cyclic-import
1489 return _utilities.RpcMethodHandler(False, True, request_deserializer,
1490 response_serializer, None, behavior,
1494 def stream_unary_rpc_method_handler(behavior,
1495 request_deserializer=None,
1496 response_serializer=None):
1497 """Creates an RpcMethodHandler for a stream-unary RPC method.
1500 behavior: The implementation of an RPC that accepts an iterator of
1501 request values and returns a single response value.
1502 request_deserializer: An optional behavior for request deserialization.
1503 response_serializer: An optional behavior for response serialization.
1506 An RpcMethodHandler object that is typically used by grpc.Server.
1508 from grpc import _utilities # pylint: disable=cyclic-import
1509 return _utilities.RpcMethodHandler(True, False, request_deserializer,
1510 response_serializer, None, None,
1514 def stream_stream_rpc_method_handler(behavior,
1515 request_deserializer=None,
1516 response_serializer=None):
1517 """Creates an RpcMethodHandler for a stream-stream RPC method.
1520 behavior: The implementation of an RPC that accepts an iterator of
1521 request values and returns an iterator of response values.
1522 request_deserializer: An optional behavior for request deserialization.
1523 response_serializer: An optional behavior for response serialization.
1526 An RpcMethodHandler object that is typically used by grpc.Server.
1528 from grpc import _utilities # pylint: disable=cyclic-import
1529 return _utilities.RpcMethodHandler(True, True, request_deserializer,
1530 response_serializer, None, None, None,
1534 def method_handlers_generic_handler(service, method_handlers):
1535 """Creates a GenericRpcHandler from RpcMethodHandlers.
1538 service: The name of the service that is implemented by the
1540 method_handlers: A dictionary that maps method names to corresponding
1544 A GenericRpcHandler. This is typically added to the grpc.Server object
1545 with add_generic_rpc_handlers() before starting the server.
1547 from grpc import _utilities # pylint: disable=cyclic-import
1548 return _utilities.DictionaryGenericHandler(service, method_handlers)
1551 def ssl_channel_credentials(root_certificates=None,
1553 certificate_chain=None):
1554 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1557 root_certificates: The PEM-encoded root certificates as a byte string,
1558 or None to retrieve them from a default location chosen by gRPC
1560 private_key: The PEM-encoded private key as a byte string, or None if no
1561 private key should be used.
1562 certificate_chain: The PEM-encoded certificate chain as a byte string
1563 to use or or None if no certificate chain should be used.
1566 A ChannelCredentials for use with an SSL-enabled Channel.
1568 return ChannelCredentials(
1569 _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1573 def metadata_call_credentials(metadata_plugin, name=None):
1574 """Construct CallCredentials from an AuthMetadataPlugin.
1577 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1578 name: An optional name for the plugin.
1583 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1584 return _plugin_wrapping.metadata_plugin_call_credentials(
1585 metadata_plugin, name)
1588 def access_token_call_credentials(access_token):
1589 """Construct CallCredentials from an access token.
1592 access_token: A string to place directly in the http request
1593 authorization header, for example
1594 "authorization: Bearer <access_token>".
1599 from grpc import _auth # pylint: disable=cyclic-import
1600 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1601 return _plugin_wrapping.metadata_plugin_call_credentials(
1602 _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1605 def composite_call_credentials(*call_credentials):
1606 """Compose multiple CallCredentials to make a new CallCredentials.
1609 *call_credentials: At least two CallCredentials objects.
1612 A CallCredentials object composed of the given CallCredentials objects.
1614 return CallCredentials(
1615 _cygrpc.CompositeCallCredentials(
1616 tuple(single_call_credentials._credentials
1617 for single_call_credentials in call_credentials)))
1620 def composite_channel_credentials(channel_credentials, *call_credentials):
1621 """Compose a ChannelCredentials and one or more CallCredentials objects.
1624 channel_credentials: A ChannelCredentials object.
1625 *call_credentials: One or more CallCredentials objects.
1628 A ChannelCredentials composed of the given ChannelCredentials and
1629 CallCredentials objects.
1631 return ChannelCredentials(
1632 _cygrpc.CompositeChannelCredentials(
1633 tuple(single_call_credentials._credentials
1634 for single_call_credentials in call_credentials),
1635 channel_credentials._credentials))
1638 def ssl_server_credentials(private_key_certificate_chain_pairs,
1639 root_certificates=None,
1640 require_client_auth=False):
1641 """Creates a ServerCredentials for use with an SSL-enabled Server.
1644 private_key_certificate_chain_pairs: A list of pairs of the form
1645 [PEM-encoded private key, PEM-encoded certificate chain].
1646 root_certificates: An optional byte string of PEM-encoded client root
1647 certificates that the server will use to verify client authentication.
1648 If omitted, require_client_auth must also be False.
1649 require_client_auth: A boolean indicating whether or not to require
1650 clients to be authenticated. May only be True if root_certificates
1654 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1655 object is an argument to add_secure_port() method during server setup.
1657 if not private_key_certificate_chain_pairs:
1659 'At least one private key-certificate chain pair is required!')
1660 elif require_client_auth and root_certificates is None:
1662 'Illegal to require client auth without providing root certificates!'
1665 return ServerCredentials(
1666 _cygrpc.server_credentials_ssl(root_certificates, [
1667 _cygrpc.SslPemKeyCertPair(key, pem)
1668 for key, pem in private_key_certificate_chain_pairs
1669 ], require_client_auth))
1672 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1673 root_certificates=None):
1674 """Creates a ServerCertificateConfiguration for use with a Server.
1677 private_key_certificate_chain_pairs: A collection of pairs of
1678 the form [PEM-encoded private key, PEM-encoded certificate
1680 root_certificates: An optional byte string of PEM-encoded client root
1681 certificates that the server will use to verify client authentication.
1684 A ServerCertificateConfiguration that can be returned in the certificate
1685 configuration fetching callback.
1687 if private_key_certificate_chain_pairs:
1688 return ServerCertificateConfiguration(
1689 _cygrpc.server_certificate_config_ssl(root_certificates, [
1690 _cygrpc.SslPemKeyCertPair(key, pem)
1691 for key, pem in private_key_certificate_chain_pairs
1695 'At least one private key-certificate chain pair is required!')
1698 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1699 certificate_configuration_fetcher,
1700 require_client_authentication=False):
1701 """Creates a ServerCredentials for use with an SSL-enabled Server.
1704 initial_certificate_configuration (ServerCertificateConfiguration): The
1705 certificate configuration with which the server will be initialized.
1706 certificate_configuration_fetcher (callable): A callable that takes no
1707 arguments and should return a ServerCertificateConfiguration to
1708 replace the server's current certificate, or None for no change
1709 (i.e., the server will continue its current certificate
1710 config). The library will call this callback on *every* new
1711 client connection before starting the TLS handshake with the
1712 client, thus allowing the user application to optionally
1713 return a new ServerCertificateConfiguration that the server will then
1714 use for the handshake.
1715 require_client_authentication: A boolean indicating whether or not to
1716 require clients to be authenticated.
1719 A ServerCredentials.
1721 return ServerCredentials(
1722 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1723 initial_certificate_configuration,
1724 certificate_configuration_fetcher, require_client_authentication))
1727 def channel_ready_future(channel):
1728 """Creates a Future that tracks when a Channel is ready.
1730 Cancelling the Future does not affect the channel's state machine.
1731 It merely decouples the Future from channel state machine.
1734 channel: A Channel object.
1737 A Future object that matures when the channel connectivity is
1738 ChannelConnectivity.READY.
1740 from grpc import _utilities # pylint: disable=cyclic-import
1741 return _utilities.channel_ready_future(channel)
1744 def insecure_channel(target, options=None, compression=None):
1745 """Creates an insecure Channel to a server.
1747 The returned Channel is thread-safe.
1750 target: The server address
1751 options: An optional list of key-value pairs (channel args
1752 in gRPC Core runtime) to configure the channel.
1753 compression: An optional value indicating the compression method to be
1754 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1759 from grpc import _channel # pylint: disable=cyclic-import
1760 return _channel.Channel(target, ()
1761 if options is None else options, None, compression)
1764 def secure_channel(target, credentials, options=None, compression=None):
1765 """Creates a secure Channel to a server.
1767 The returned Channel is thread-safe.
1770 target: The server address.
1771 credentials: A ChannelCredentials instance.
1772 options: An optional list of key-value pairs (channel args
1773 in gRPC Core runtime) to configure the channel.
1774 compression: An optional value indicating the compression method to be
1775 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1780 from grpc import _channel # pylint: disable=cyclic-import
1781 return _channel.Channel(target, () if options is None else options,
1782 credentials._credentials, compression)
1785 def intercept_channel(channel, *interceptors):
1786 """Intercepts a channel through a set of interceptors.
1788 This is an EXPERIMENTAL API.
1792 interceptors: Zero or more objects of type
1793 UnaryUnaryClientInterceptor,
1794 UnaryStreamClientInterceptor,
1795 StreamUnaryClientInterceptor, or
1796 StreamStreamClientInterceptor.
1797 Interceptors are given control in the order they are listed.
1800 A Channel that intercepts each invocation via the provided interceptors.
1803 TypeError: If interceptor does not derive from any of
1804 UnaryUnaryClientInterceptor,
1805 UnaryStreamClientInterceptor,
1806 StreamUnaryClientInterceptor, or
1807 StreamStreamClientInterceptor.
1809 from grpc import _interceptor # pylint: disable=cyclic-import
1810 return _interceptor.intercept_channel(channel, *interceptors)
1813 def server(thread_pool,
1817 maximum_concurrent_rpcs=None,
1819 """Creates a Server with which RPCs can be serviced.
1822 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
1823 to execute RPC handlers.
1824 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
1825 More handlers may be added by calling add_generic_rpc_handlers any time
1826 before the server is started.
1827 interceptors: An optional list of ServerInterceptor objects that observe
1828 and optionally manipulate the incoming RPCs before handing them over to
1829 handlers. The interceptors are given control in the order they are
1830 specified. This is an EXPERIMENTAL API.
1831 options: An optional list of key-value pairs (channel args in gRPC runtime)
1832 to configure the channel.
1833 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
1834 will service before returning RESOURCE_EXHAUSTED status, or None to
1836 compression: An element of grpc.compression, e.g.
1837 grpc.compression.Gzip. This compression algorithm will be used for the
1838 lifetime of the server unless overridden. This is an EXPERIMENTAL option.
1843 from grpc import _server # pylint: disable=cyclic-import
1844 return _server.create_server(thread_pool, ()
1845 if handlers is None else handlers, ()
1846 if interceptors is None else interceptors, ()
1847 if options is None else options,
1848 maximum_concurrent_rpcs, compression)
1851 @contextlib.contextmanager
1852 def _create_servicer_context(rpc_event, state, request_deserializer):
1853 from grpc import _server # pylint: disable=cyclic-import
1854 context = _server._Context(rpc_event, state, request_deserializer)
1856 context._finalize_state() # pylint: disable=protected-access
1859 class Compression(enum.IntEnum):
1860 """Indicates the compression method to be used for an RPC.
1862 This enumeration is part of an EXPERIMENTAL API.
1864 NoCompression = _compression.NoCompression
1865 Deflate = _compression.Deflate
1866 Gzip = _compression.Gzip
1869 ################################### __all__ #################################
1872 'FutureTimeoutError',
1873 'FutureCancelledError',
1875 'ChannelConnectivity',
1881 'ChannelCredentials',
1883 'AuthMetadataContext',
1884 'AuthMetadataPluginCallback',
1885 'AuthMetadataPlugin',
1887 'ClientCallDetails',
1888 'ServerCertificateConfiguration',
1889 'ServerCredentials',
1890 'UnaryUnaryMultiCallable',
1891 'UnaryStreamMultiCallable',
1892 'StreamUnaryMultiCallable',
1893 'StreamStreamMultiCallable',
1894 'UnaryUnaryClientInterceptor',
1895 'UnaryStreamClientInterceptor',
1896 'StreamUnaryClientInterceptor',
1897 'StreamStreamClientInterceptor',
1901 'HandlerCallDetails',
1902 'GenericRpcHandler',
1903 'ServiceRpcHandler',
1905 'ServerInterceptor',
1906 'unary_unary_rpc_method_handler',
1907 'unary_stream_rpc_method_handler',
1908 'stream_unary_rpc_method_handler',
1909 'stream_stream_rpc_method_handler',
1910 'method_handlers_generic_handler',
1911 'ssl_channel_credentials',
1912 'metadata_call_credentials',
1913 'access_token_call_credentials',
1914 'composite_call_credentials',
1915 'composite_channel_credentials',
1916 'ssl_server_credentials',
1917 'ssl_server_certificate_configuration',
1918 'dynamic_ssl_server_credentials',
1919 'channel_ready_future',
1922 'intercept_channel',
1926 ############################### Extension Shims ################################
1928 # Here to maintain backwards compatibility; avoid using these in new code!
1931 sys.modules.update({'grpc.tools': grpc_tools})
1936 sys.modules.update({'grpc.health': grpc_health})
1940 import grpc_reflection
1941 sys.modules.update({'grpc.reflection': grpc_reflection})