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.
342 True if the callback was added and will be called later; False if
343 the callback was not added and will not be called (because the RPC
344 already terminated or some other reason).
346 raise NotImplementedError()
349 ######################### Invocation-Side Context ############################
352 class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
353 """Invocation-side utility object for an RPC."""
356 def initial_metadata(self):
357 """Accesses the initial metadata sent by the server.
359 This method blocks until the value is available.
362 The initial :term:`metadata`.
364 raise NotImplementedError()
367 def trailing_metadata(self):
368 """Accesses the trailing metadata sent by the server.
370 This method blocks until the value is available.
373 The trailing :term:`metadata`.
375 raise NotImplementedError()
379 """Accesses the status code sent by the server.
381 This method blocks until the value is available.
384 The StatusCode value for the RPC.
386 raise NotImplementedError()
390 """Accesses the details sent by the server.
392 This method blocks until the value is available.
395 The details string of the RPC.
397 raise NotImplementedError()
400 ############## Invocation-Side Interceptor Interfaces & Classes ##############
403 class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
404 """Describes an RPC to be invoked.
406 This is an EXPERIMENTAL API.
409 method: The method name of the RPC.
410 timeout: An optional duration of time in seconds to allow for the RPC.
411 metadata: Optional :term:`metadata` to be transmitted to
412 the service-side of the RPC.
413 credentials: An optional CallCredentials for the RPC.
414 wait_for_ready: This is an EXPERIMENTAL argument. An optional flag t
415 enable wait for ready mechanism.
416 compression: An element of grpc.compression, e.g.
417 grpc.compression.Gzip. This is an EXPERIMENTAL option.
421 class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
422 """Affords intercepting unary-unary invocations.
424 This is an EXPERIMENTAL API.
428 def intercept_unary_unary(self, continuation, client_call_details, request):
429 """Intercepts a unary-unary invocation asynchronously.
432 continuation: A function that proceeds with the invocation by
433 executing the next interceptor in chain or invoking the
434 actual RPC on the underlying Channel. It is the interceptor's
435 responsibility to call it if it decides to move the RPC forward.
436 The interceptor can use
437 `response_future = continuation(client_call_details, request)`
438 to continue with the RPC. `continuation` returns an object that is
439 both a Call for the RPC and a Future. In the event of RPC
440 completion, the return Call-Future's result value will be
441 the response message of the RPC. Should the event terminate
442 with non-OK status, the returned Call-Future's exception value
444 client_call_details: A ClientCallDetails object describing the
446 request: The request value for the RPC.
449 An object that is both a Call for the RPC and a Future.
450 In the event of RPC completion, the return Call-Future's
451 result value will be the response message of the RPC.
452 Should the event terminate with non-OK status, the returned
453 Call-Future's exception value will be an RpcError.
455 raise NotImplementedError()
458 class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
459 """Affords intercepting unary-stream invocations.
461 This is an EXPERIMENTAL API.
465 def intercept_unary_stream(self, continuation, client_call_details,
467 """Intercepts a unary-stream invocation.
470 continuation: A function that proceeds with the invocation by
471 executing the next interceptor in chain or invoking the
472 actual RPC on the underlying Channel. It is the interceptor's
473 responsibility to call it if it decides to move the RPC forward.
474 The interceptor can use
475 `response_iterator = continuation(client_call_details, request)`
476 to continue with the RPC. `continuation` returns an object that is
477 both a Call for the RPC and an iterator for response values.
478 Drawing response values from the returned Call-iterator may
479 raise RpcError indicating termination of the RPC with non-OK
481 client_call_details: A ClientCallDetails object describing the
483 request: The request value for the RPC.
486 An object that is both a Call for the RPC and an iterator of
487 response values. Drawing response values from the returned
488 Call-iterator may raise RpcError indicating termination of
489 the RPC with non-OK status.
491 raise NotImplementedError()
494 class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
495 """Affords intercepting stream-unary invocations.
497 This is an EXPERIMENTAL API.
501 def intercept_stream_unary(self, continuation, client_call_details,
503 """Intercepts a stream-unary invocation asynchronously.
506 continuation: A function that proceeds with the invocation by
507 executing the next interceptor in chain or invoking the
508 actual RPC on the underlying Channel. It is the interceptor's
509 responsibility to call it if it decides to move the RPC forward.
510 The interceptor can use
511 `response_future = continuation(client_call_details, request_iterator)`
512 to continue with the RPC. `continuation` returns an object that is
513 both a Call for the RPC and a Future. In the event of RPC completion,
514 the return Call-Future's result value will be the response message
515 of the RPC. Should the event terminate with non-OK status, the
516 returned Call-Future's exception value will be an RpcError.
517 client_call_details: A ClientCallDetails object describing the
519 request_iterator: An iterator that yields request values for the RPC.
522 An object that is both a Call for the RPC and a Future.
523 In the event of RPC completion, the return Call-Future's
524 result value will be the response message of the RPC.
525 Should the event terminate with non-OK status, the returned
526 Call-Future's exception value will be an RpcError.
528 raise NotImplementedError()
531 class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
532 """Affords intercepting stream-stream invocations.
534 This is an EXPERIMENTAL API.
538 def intercept_stream_stream(self, continuation, client_call_details,
540 """Intercepts a stream-stream invocation.
543 continuation: A function that proceeds with the invocation by
544 executing the next interceptor in chain or invoking the
545 actual RPC on the underlying Channel. It is the interceptor's
546 responsibility to call it if it decides to move the RPC forward.
547 The interceptor can use
548 `response_iterator = continuation(client_call_details, request_iterator)`
549 to continue with the RPC. `continuation` returns an object that is
550 both a Call for the RPC and an iterator for response values.
551 Drawing response values from the returned Call-iterator may
552 raise RpcError indicating termination of the RPC with non-OK
554 client_call_details: A ClientCallDetails object describing the
556 request_iterator: An iterator that yields request values for the RPC.
559 An object that is both a Call for the RPC and an iterator of
560 response values. Drawing response values from the returned
561 Call-iterator may raise RpcError indicating termination of
562 the RPC with non-OK status.
564 raise NotImplementedError()
567 ############ Authentication & Authorization Interfaces & Classes #############
570 class ChannelCredentials(object):
571 """An encapsulation of the data required to create a secure Channel.
573 This class has no supported interface - it exists to define the type of its
574 instances and its instances exist to be passed to other functions. For
575 example, ssl_channel_credentials returns an instance of this class and
576 secure_channel requires an instance of this class.
579 def __init__(self, credentials):
580 self._credentials = credentials
583 class CallCredentials(object):
584 """An encapsulation of the data required to assert an identity over a call.
586 A CallCredentials has to be used with secure Channel, otherwise the
587 metadata will not be transmitted to the server.
589 A CallCredentials may be composed with ChannelCredentials to always assert
590 identity for every call over that Channel.
592 This class has no supported interface - it exists to define the type of its
593 instances and its instances exist to be passed to other functions.
596 def __init__(self, credentials):
597 self._credentials = credentials
600 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
601 """Provides information to call credentials metadata plugins.
604 service_url: A string URL of the service being called into.
605 method_name: A string of the fully qualified method name being called.
609 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
610 """Callback object received by a metadata plugin."""
612 def __call__(self, metadata, error):
613 """Passes to the gRPC runtime authentication metadata for an RPC.
616 metadata: The :term:`metadata` used to construct the CallCredentials.
617 error: An Exception to indicate error or None to indicate success.
619 raise NotImplementedError()
622 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
623 """A specification for custom authentication."""
625 def __call__(self, context, callback):
626 """Implements authentication by passing metadata to a callback.
628 Implementations of this method must not block.
631 context: An AuthMetadataContext providing information on the RPC that
632 the plugin is being called to authenticate.
633 callback: An AuthMetadataPluginCallback to be invoked either
634 synchronously or asynchronously.
636 raise NotImplementedError()
639 class ServerCredentials(object):
640 """An encapsulation of the data required to open a secure port on a Server.
642 This class has no supported interface - it exists to define the type of its
643 instances and its instances exist to be passed to other functions.
646 def __init__(self, credentials):
647 self._credentials = credentials
650 class ServerCertificateConfiguration(object):
651 """A certificate configuration for use with an SSL-enabled Server.
653 Instances of this class can be returned in the certificate configuration
656 This class has no supported interface -- it exists to define the
657 type of its instances and its instances exist to be passed to
661 def __init__(self, certificate_configuration):
662 self._certificate_configuration = certificate_configuration
665 ######################## Multi-Callable Interfaces ###########################
668 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
669 """Affords invoking a unary-unary RPC from client-side."""
679 """Synchronously invokes the underlying RPC.
682 request: The request value for the RPC.
683 timeout: An optional duration of time in seconds to allow
685 metadata: Optional :term:`metadata` to be transmitted to the
686 service-side of the RPC.
687 credentials: An optional CallCredentials for the RPC. Only valid for
689 wait_for_ready: This is an EXPERIMENTAL argument. An optional
690 flag to enable wait for ready mechanism
691 compression: An element of grpc.compression, e.g.
692 grpc.compression.Gzip. This is an EXPERIMENTAL option.
695 The response value for the RPC.
698 RpcError: Indicating that the RPC terminated with non-OK status. The
699 raised RpcError will also be a Call for the RPC affording the RPC's
700 metadata, status code, and details.
702 raise NotImplementedError()
712 """Synchronously invokes the underlying RPC.
715 request: The request value for the RPC.
716 timeout: An optional durating of time in seconds to allow for
718 metadata: Optional :term:`metadata` to be transmitted to the
719 service-side of the RPC.
720 credentials: An optional CallCredentials for the RPC. Only valid for
722 wait_for_ready: This is an EXPERIMENTAL argument. An optional
723 flag to enable wait for ready mechanism
724 compression: An element of grpc.compression, e.g.
725 grpc.compression.Gzip. This is an EXPERIMENTAL option.
728 The response value for the RPC and a Call value for the RPC.
731 RpcError: Indicating that the RPC terminated with non-OK status. The
732 raised RpcError will also be a Call for the RPC affording the RPC's
733 metadata, status code, and details.
735 raise NotImplementedError()
745 """Asynchronously invokes the underlying RPC.
748 request: The request value for the RPC.
749 timeout: An optional duration of time in seconds to allow for
751 metadata: Optional :term:`metadata` to be transmitted to the
752 service-side of the RPC.
753 credentials: An optional CallCredentials for the RPC. Only valid for
755 wait_for_ready: This is an EXPERIMENTAL argument. An optional
756 flag to enable wait for ready mechanism
757 compression: An element of grpc.compression, e.g.
758 grpc.compression.Gzip. This is an EXPERIMENTAL option.
761 An object that is both a Call for the RPC and a Future.
762 In the event of RPC completion, the return Call-Future's result
763 value will be the response message of the RPC.
764 Should the event terminate with non-OK status,
765 the returned Call-Future's exception value will be an RpcError.
767 raise NotImplementedError()
770 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
771 """Affords invoking a unary-stream RPC from client-side."""
781 """Invokes the underlying RPC.
784 request: The request value for the RPC.
785 timeout: An optional duration of time in seconds to allow for
786 the RPC. If None, the timeout is considered infinite.
787 metadata: An optional :term:`metadata` to be transmitted to the
788 service-side of the RPC.
789 credentials: An optional CallCredentials for the RPC. Only valid for
791 wait_for_ready: This is an EXPERIMENTAL argument. An optional
792 flag to enable wait for ready mechanism
793 compression: An element of grpc.compression, e.g.
794 grpc.compression.Gzip. This is an EXPERIMENTAL option.
797 An object that is both a Call for the RPC and an iterator of
798 response values. Drawing response values from the returned
799 Call-iterator may raise RpcError indicating termination of the
800 RPC with non-OK status.
802 raise NotImplementedError()
805 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
806 """Affords invoking a stream-unary RPC from client-side."""
816 """Synchronously invokes the underlying RPC.
819 request_iterator: An iterator that yields request values for
821 timeout: An optional duration of time in seconds to allow for
822 the RPC. If None, the timeout is considered infinite.
823 metadata: Optional :term:`metadata` to be transmitted to the
824 service-side of the RPC.
825 credentials: An optional CallCredentials for the RPC. Only valid for
827 wait_for_ready: This is an EXPERIMENTAL argument. An optional
828 flag to enable wait for ready mechanism
829 compression: An element of grpc.compression, e.g.
830 grpc.compression.Gzip. This is an EXPERIMENTAL option.
833 The response value for the RPC.
836 RpcError: Indicating that the RPC terminated with non-OK status. The
837 raised RpcError will also implement grpc.Call, affording methods
838 such as metadata, code, and details.
840 raise NotImplementedError()
850 """Synchronously invokes the underlying RPC on the client.
853 request_iterator: An iterator that yields request values for
855 timeout: An optional duration of time in seconds to allow for
856 the RPC. If None, the timeout is considered infinite.
857 metadata: Optional :term:`metadata` to be transmitted to the
858 service-side of the RPC.
859 credentials: An optional CallCredentials for the RPC. Only valid for
861 wait_for_ready: This is an EXPERIMENTAL argument. An optional
862 flag to enable wait for ready mechanism
863 compression: An element of grpc.compression, e.g.
864 grpc.compression.Gzip. This is an EXPERIMENTAL option.
867 The response value for the RPC and a Call object for the RPC.
870 RpcError: Indicating that the RPC terminated with non-OK status. The
871 raised RpcError will also be a Call for the RPC affording the RPC's
872 metadata, status code, and details.
874 raise NotImplementedError()
884 """Asynchronously invokes the underlying RPC on the client.
887 request_iterator: An iterator that yields request values for the RPC.
888 timeout: An optional duration of time in seconds to allow for
889 the RPC. If None, the timeout is considered infinite.
890 metadata: Optional :term:`metadata` to be transmitted to the
891 service-side of the RPC.
892 credentials: An optional CallCredentials for the RPC. Only valid for
894 wait_for_ready: This is an EXPERIMENTAL argument. An optional
895 flag to enable wait for ready mechanism
896 compression: An element of grpc.compression, e.g.
897 grpc.compression.Gzip. This is an EXPERIMENTAL option.
900 An object that is both a Call for the RPC and a Future.
901 In the event of RPC completion, the return Call-Future's result value
902 will be the response message of the RPC. Should the event terminate
903 with non-OK status, the returned Call-Future's exception value will
906 raise NotImplementedError()
909 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
910 """Affords invoking a stream-stream RPC on client-side."""
920 """Invokes the underlying RPC on the client.
923 request_iterator: An iterator that yields request values for the RPC.
924 timeout: An optional duration of time in seconds to allow for
925 the RPC. If not specified, the timeout is considered infinite.
926 metadata: Optional :term:`metadata` to be transmitted to the
927 service-side of the RPC.
928 credentials: An optional CallCredentials for the RPC. Only valid for
930 wait_for_ready: This is an EXPERIMENTAL argument. An optional
931 flag to enable wait for ready mechanism
932 compression: An element of grpc.compression, e.g.
933 grpc.compression.Gzip. This is an EXPERIMENTAL option.
936 An object that is both a Call for the RPC and an iterator of
937 response values. Drawing response values from the returned
938 Call-iterator may raise RpcError indicating termination of the
939 RPC with non-OK status.
941 raise NotImplementedError()
944 ############################# Channel Interface ##############################
947 class Channel(six.with_metaclass(abc.ABCMeta)):
948 """Affords RPC invocation via generic methods on client-side.
950 Channel objects implement the Context Manager type, although they need not
951 support being entered and exited multiple times.
955 def subscribe(self, callback, try_to_connect=False):
956 """Subscribe to this Channel's connectivity state machine.
958 A Channel may be in any of the states described by ChannelConnectivity.
959 This method allows application to monitor the state transitions.
960 The typical use case is to debug or gain better visibility into gRPC
964 callback: A callable to be invoked with ChannelConnectivity argument.
965 ChannelConnectivity describes current state of the channel.
966 The callable will be invoked immediately upon subscription
967 and again for every change to ChannelConnectivity until it
968 is unsubscribed or this Channel object goes out of scope.
969 try_to_connect: A boolean indicating whether or not this Channel
970 should attempt to connect immediately. If set to False, gRPC
971 runtime decides when to connect.
973 raise NotImplementedError()
976 def unsubscribe(self, callback):
977 """Unsubscribes a subscribed callback from this Channel's connectivity.
980 callback: A callable previously registered with this Channel from
981 having been passed to its "subscribe" method.
983 raise NotImplementedError()
986 def unary_unary(self,
988 request_serializer=None,
989 response_deserializer=None):
990 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
993 method: The name of the RPC method.
994 request_serializer: Optional behaviour for serializing the request
995 message. Request goes unserialized in case None is passed.
996 response_deserializer: Optional behaviour for deserializing the
997 response message. Response goes undeserialized in case None
1001 A UnaryUnaryMultiCallable value for the named unary-unary method.
1003 raise NotImplementedError()
1006 def unary_stream(self,
1008 request_serializer=None,
1009 response_deserializer=None):
1010 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1013 method: The name of the RPC method.
1014 request_serializer: Optional behaviour for serializing the request
1015 message. Request goes unserialized in case None is passed.
1016 response_deserializer: Optional behaviour for deserializing the
1017 response message. Response goes undeserialized in case None is
1021 A UnaryStreamMultiCallable value for the name unary-stream method.
1023 raise NotImplementedError()
1026 def stream_unary(self,
1028 request_serializer=None,
1029 response_deserializer=None):
1030 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1033 method: The name of the RPC method.
1034 request_serializer: Optional behaviour for serializing the request
1035 message. Request goes unserialized in case None is passed.
1036 response_deserializer: Optional behaviour for deserializing the
1037 response message. Response goes undeserialized in case None is
1041 A StreamUnaryMultiCallable value for the named stream-unary method.
1043 raise NotImplementedError()
1046 def stream_stream(self,
1048 request_serializer=None,
1049 response_deserializer=None):
1050 """Creates a StreamStreamMultiCallable for a stream-stream method.
1053 method: The name of the RPC method.
1054 request_serializer: Optional behaviour for serializing the request
1055 message. Request goes unserialized in case None is passed.
1056 response_deserializer: Optional behaviour for deserializing the
1057 response message. Response goes undeserialized in case None
1061 A StreamStreamMultiCallable value for the named stream-stream method.
1063 raise NotImplementedError()
1067 """Closes this Channel and releases all resources held by it.
1069 Closing the Channel will immediately terminate all RPCs active with the
1070 Channel and it is not valid to invoke new RPCs with the Channel.
1072 This method is idempotent.
1074 raise NotImplementedError()
1077 ########################## Service-Side Context ##############################
1080 class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1081 """A context object passed to method implementations."""
1084 def invocation_metadata(self):
1085 """Accesses the metadata from the sent by the client.
1088 The invocation :term:`metadata`.
1090 raise NotImplementedError()
1094 """Identifies the peer that invoked the RPC being serviced.
1097 A string identifying the peer that invoked the RPC being serviced.
1098 The string format is determined by gRPC runtime.
1100 raise NotImplementedError()
1103 def peer_identities(self):
1104 """Gets one or more peer identity(s).
1107 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1110 An iterable of the identities, or None if the call is not
1111 authenticated. Each identity is returned as a raw bytes type.
1113 raise NotImplementedError()
1116 def peer_identity_key(self):
1117 """The auth property used to identify the peer.
1119 For example, "x509_common_name" or "x509_subject_alternative_name" are
1120 used to identify an SSL peer.
1123 The auth property (string) that indicates the
1124 peer identity, or None if the call is not authenticated.
1126 raise NotImplementedError()
1129 def auth_context(self):
1130 """Gets the auth context for the call.
1133 A map of strings to an iterable of bytes for each auth property.
1135 raise NotImplementedError()
1137 def set_compression(self, compression):
1138 """Set the compression algorithm to be used for the entire call.
1140 This is an EXPERIMENTAL method.
1143 compression: An element of grpc.compression, e.g.
1144 grpc.compression.Gzip.
1146 raise NotImplementedError()
1149 def send_initial_metadata(self, initial_metadata):
1150 """Sends the initial metadata value to the client.
1152 This method need not be called by implementations if they have no
1153 metadata to add to what the gRPC runtime will transmit.
1156 initial_metadata: The initial :term:`metadata`.
1158 raise NotImplementedError()
1161 def set_trailing_metadata(self, trailing_metadata):
1162 """Sends the trailing metadata for the RPC.
1164 This method need not be called by implementations if they have no
1165 metadata to add to what the gRPC runtime will transmit.
1168 trailing_metadata: The trailing :term:`metadata`.
1170 raise NotImplementedError()
1173 def abort(self, code, details):
1174 """Raises an exception to terminate the RPC with a non-OK status.
1176 The code and details passed as arguments will supercede any existing
1180 code: A StatusCode object to be sent to the client.
1181 It must not be StatusCode.OK.
1182 details: A UTF-8-encodable string to be sent to the client upon
1183 termination of the RPC.
1186 Exception: An exception is always raised to signal the abortion the
1187 RPC to the gRPC runtime.
1189 raise NotImplementedError()
1192 def abort_with_status(self, status):
1193 """Raises an exception to terminate the RPC with a non-OK status.
1195 The status passed as argument will supercede any existing status code,
1196 status message and trailing metadata.
1198 This is an EXPERIMENTAL API.
1201 status: A grpc.Status object. The status code in it must not be
1205 Exception: An exception is always raised to signal the abortion the
1206 RPC to the gRPC runtime.
1208 raise NotImplementedError()
1211 def set_code(self, code):
1212 """Sets the value to be used as status code upon RPC completion.
1214 This method need not be called by method implementations if they wish
1215 the gRPC runtime to determine the status code of the RPC.
1218 code: A StatusCode object to be sent to the client.
1220 raise NotImplementedError()
1223 def set_details(self, details):
1224 """Sets the value to be used as detail string upon RPC completion.
1226 This method need not be called by method implementations if they have
1227 no details to transmit.
1230 details: A UTF-8-encodable string to be sent to the client upon
1231 termination of the RPC.
1233 raise NotImplementedError()
1235 def disable_next_message_compression(self):
1236 """Disables compression for the next response message.
1238 This is an EXPERIMENTAL method.
1240 This method will override any compression configuration set during
1241 server creation or set on the call.
1243 raise NotImplementedError()
1246 ##################### Service-Side Handler Interfaces ########################
1249 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1250 """An implementation of a single RPC method.
1253 request_streaming: Whether the RPC supports exactly one request message
1254 or any arbitrary number of request messages.
1255 response_streaming: Whether the RPC supports exactly one response message
1256 or any arbitrary number of response messages.
1257 request_deserializer: A callable behavior that accepts a byte string and
1258 returns an object suitable to be passed to this object's business
1259 logic, or None to indicate that this object's business logic should be
1260 passed the raw request bytes.
1261 response_serializer: A callable behavior that accepts an object produced
1262 by this object's business logic and returns a byte string, or None to
1263 indicate that the byte strings produced by this object's business logic
1264 should be transmitted on the wire as they are.
1265 unary_unary: This object's application-specific business logic as a
1266 callable value that takes a request value and a ServicerContext object
1267 and returns a response value. Only non-None if both request_streaming
1268 and response_streaming are False.
1269 unary_stream: This object's application-specific business logic as a
1270 callable value that takes a request value and a ServicerContext object
1271 and returns an iterator of response values. Only non-None if
1272 request_streaming is False and response_streaming is True.
1273 stream_unary: This object's application-specific business logic as a
1274 callable value that takes an iterator of request values and a
1275 ServicerContext object and returns a response value. Only non-None if
1276 request_streaming is True and response_streaming is False.
1277 stream_stream: This object's application-specific business logic as a
1278 callable value that takes an iterator of request values and a
1279 ServicerContext object and returns an iterator of response values.
1280 Only non-None if request_streaming and response_streaming are both
1285 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1286 """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. If the port is 0,
1385 or not specified in the address, then gRPC runtime will choose a port.
1388 An integer port on which server will accept RPC requests.
1390 raise NotImplementedError()
1393 def add_secure_port(self, address, server_credentials):
1394 """Opens a secure port for accepting RPCs.
1396 This method may only be called before starting the server.
1399 address: The address for which to open a port.
1400 if the port is 0, or not specified in the address, then gRPC
1401 runtime will choose a port.
1402 server_credentials: A ServerCredentials object.
1405 An integer port on which server will accept RPC requests.
1407 raise NotImplementedError()
1411 """Starts this Server.
1413 This method may only be called once. (i.e. it is not idempotent).
1415 raise NotImplementedError()
1418 def stop(self, grace):
1419 """Stops this Server.
1421 This method immediately stop service of new RPCs in all cases.
1423 If a grace period is specified, this method returns immediately
1424 and all RPCs active at the end of the grace period are aborted.
1425 If a grace period is not specified (by passing None for `grace`),
1426 all existing RPCs are aborted immediately and this method
1427 blocks until the last RPC handler terminates.
1429 This method is idempotent and may be called at any time.
1430 Passing a smaller grace value in a subsequent call will have
1431 the effect of stopping the Server sooner (passing None will
1432 have the effect of stopping the server immediately). Passing
1433 a larger grace value in a subsequent call *will not* have the
1434 effect of stopping the server later (i.e. the most restrictive
1435 grace value is used).
1438 grace: A duration of time in seconds or None.
1441 A threading.Event that will be set when this Server has completely
1442 stopped, i.e. when running RPCs either complete or are aborted and
1443 all handlers have terminated.
1445 raise NotImplementedError()
1448 ################################# Functions ################################
1451 def unary_unary_rpc_method_handler(behavior,
1452 request_deserializer=None,
1453 response_serializer=None):
1454 """Creates an RpcMethodHandler for a unary-unary RPC method.
1457 behavior: The implementation of an RPC that accepts one request
1458 and returns one response.
1459 request_deserializer: An optional behavior for request deserialization.
1460 response_serializer: An optional behavior for response serialization.
1463 An RpcMethodHandler object that is typically used by grpc.Server.
1465 from grpc import _utilities # pylint: disable=cyclic-import
1466 return _utilities.RpcMethodHandler(False, False, request_deserializer,
1467 response_serializer, behavior, None,
1471 def unary_stream_rpc_method_handler(behavior,
1472 request_deserializer=None,
1473 response_serializer=None):
1474 """Creates an RpcMethodHandler for a unary-stream RPC method.
1477 behavior: The implementation of an RPC that accepts one request
1478 and returns an iterator of response values.
1479 request_deserializer: An optional behavior for request deserialization.
1480 response_serializer: An optional behavior for response serialization.
1483 An RpcMethodHandler object that is typically used by grpc.Server.
1485 from grpc import _utilities # pylint: disable=cyclic-import
1486 return _utilities.RpcMethodHandler(False, True, request_deserializer,
1487 response_serializer, None, behavior,
1491 def stream_unary_rpc_method_handler(behavior,
1492 request_deserializer=None,
1493 response_serializer=None):
1494 """Creates an RpcMethodHandler for a stream-unary RPC method.
1497 behavior: The implementation of an RPC that accepts an iterator of
1498 request values and returns a single response value.
1499 request_deserializer: An optional behavior for request deserialization.
1500 response_serializer: An optional behavior for response serialization.
1503 An RpcMethodHandler object that is typically used by grpc.Server.
1505 from grpc import _utilities # pylint: disable=cyclic-import
1506 return _utilities.RpcMethodHandler(True, False, request_deserializer,
1507 response_serializer, None, None,
1511 def stream_stream_rpc_method_handler(behavior,
1512 request_deserializer=None,
1513 response_serializer=None):
1514 """Creates an RpcMethodHandler for a stream-stream RPC method.
1517 behavior: The implementation of an RPC that accepts an iterator of
1518 request values and returns an iterator of response values.
1519 request_deserializer: An optional behavior for request deserialization.
1520 response_serializer: An optional behavior for response serialization.
1523 An RpcMethodHandler object that is typically used by grpc.Server.
1525 from grpc import _utilities # pylint: disable=cyclic-import
1526 return _utilities.RpcMethodHandler(True, True, request_deserializer,
1527 response_serializer, None, None, None,
1531 def method_handlers_generic_handler(service, method_handlers):
1532 """Creates a GenericRpcHandler from RpcMethodHandlers.
1535 service: The name of the service that is implemented by the
1537 method_handlers: A dictionary that maps method names to corresponding
1541 A GenericRpcHandler. This is typically added to the grpc.Server object
1542 with add_generic_rpc_handlers() before starting the server.
1544 from grpc import _utilities # pylint: disable=cyclic-import
1545 return _utilities.DictionaryGenericHandler(service, method_handlers)
1548 def ssl_channel_credentials(root_certificates=None,
1550 certificate_chain=None):
1551 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1554 root_certificates: The PEM-encoded root certificates as a byte string,
1555 or None to retrieve them from a default location chosen by gRPC
1557 private_key: The PEM-encoded private key as a byte string, or None if no
1558 private key should be used.
1559 certificate_chain: The PEM-encoded certificate chain as a byte string
1560 to use or or None if no certificate chain should be used.
1563 A ChannelCredentials for use with an SSL-enabled Channel.
1565 return ChannelCredentials(
1566 _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1570 def metadata_call_credentials(metadata_plugin, name=None):
1571 """Construct CallCredentials from an AuthMetadataPlugin.
1574 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1575 name: An optional name for the plugin.
1580 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1581 return _plugin_wrapping.metadata_plugin_call_credentials(
1582 metadata_plugin, name)
1585 def access_token_call_credentials(access_token):
1586 """Construct CallCredentials from an access token.
1589 access_token: A string to place directly in the http request
1590 authorization header, for example
1591 "authorization: Bearer <access_token>".
1596 from grpc import _auth # pylint: disable=cyclic-import
1597 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1598 return _plugin_wrapping.metadata_plugin_call_credentials(
1599 _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1602 def composite_call_credentials(*call_credentials):
1603 """Compose multiple CallCredentials to make a new CallCredentials.
1606 *call_credentials: At least two CallCredentials objects.
1609 A CallCredentials object composed of the given CallCredentials objects.
1611 return CallCredentials(
1612 _cygrpc.CompositeCallCredentials(
1613 tuple(single_call_credentials._credentials
1614 for single_call_credentials in call_credentials)))
1617 def composite_channel_credentials(channel_credentials, *call_credentials):
1618 """Compose a ChannelCredentials and one or more CallCredentials objects.
1621 channel_credentials: A ChannelCredentials object.
1622 *call_credentials: One or more CallCredentials objects.
1625 A ChannelCredentials composed of the given ChannelCredentials and
1626 CallCredentials objects.
1628 return ChannelCredentials(
1629 _cygrpc.CompositeChannelCredentials(
1630 tuple(single_call_credentials._credentials
1631 for single_call_credentials in call_credentials),
1632 channel_credentials._credentials))
1635 def ssl_server_credentials(private_key_certificate_chain_pairs,
1636 root_certificates=None,
1637 require_client_auth=False):
1638 """Creates a ServerCredentials for use with an SSL-enabled Server.
1641 private_key_certificate_chain_pairs: A list of pairs of the form
1642 [PEM-encoded private key, PEM-encoded certificate chain].
1643 root_certificates: An optional byte string of PEM-encoded client root
1644 certificates that the server will use to verify client authentication.
1645 If omitted, require_client_auth must also be False.
1646 require_client_auth: A boolean indicating whether or not to require
1647 clients to be authenticated. May only be True if root_certificates
1651 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1652 object is an argument to add_secure_port() method during server setup.
1654 if not private_key_certificate_chain_pairs:
1656 'At least one private key-certificate chain pair is required!')
1657 elif require_client_auth and root_certificates is None:
1659 'Illegal to require client auth without providing root certificates!'
1662 return ServerCredentials(
1663 _cygrpc.server_credentials_ssl(root_certificates, [
1664 _cygrpc.SslPemKeyCertPair(key, pem)
1665 for key, pem in private_key_certificate_chain_pairs
1666 ], require_client_auth))
1669 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1670 root_certificates=None):
1671 """Creates a ServerCertificateConfiguration for use with a Server.
1674 private_key_certificate_chain_pairs: A collection of pairs of
1675 the form [PEM-encoded private key, PEM-encoded certificate
1677 root_certificates: An optional byte string of PEM-encoded client root
1678 certificates that the server will use to verify client authentication.
1681 A ServerCertificateConfiguration that can be returned in the certificate
1682 configuration fetching callback.
1684 if private_key_certificate_chain_pairs:
1685 return ServerCertificateConfiguration(
1686 _cygrpc.server_certificate_config_ssl(root_certificates, [
1687 _cygrpc.SslPemKeyCertPair(key, pem)
1688 for key, pem in private_key_certificate_chain_pairs
1692 'At least one private key-certificate chain pair is required!')
1695 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1696 certificate_configuration_fetcher,
1697 require_client_authentication=False):
1698 """Creates a ServerCredentials for use with an SSL-enabled Server.
1701 initial_certificate_configuration (ServerCertificateConfiguration): The
1702 certificate configuration with which the server will be initialized.
1703 certificate_configuration_fetcher (callable): A callable that takes no
1704 arguments and should return a ServerCertificateConfiguration to
1705 replace the server's current certificate, or None for no change
1706 (i.e., the server will continue its current certificate
1707 config). The library will call this callback on *every* new
1708 client connection before starting the TLS handshake with the
1709 client, thus allowing the user application to optionally
1710 return a new ServerCertificateConfiguration that the server will then
1711 use for the handshake.
1712 require_client_authentication: A boolean indicating whether or not to
1713 require clients to be authenticated.
1716 A ServerCredentials.
1718 return ServerCredentials(
1719 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1720 initial_certificate_configuration,
1721 certificate_configuration_fetcher, require_client_authentication))
1724 def channel_ready_future(channel):
1725 """Creates a Future that tracks when a Channel is ready.
1727 Cancelling the Future does not affect the channel's state machine.
1728 It merely decouples the Future from channel state machine.
1731 channel: A Channel object.
1734 A Future object that matures when the channel connectivity is
1735 ChannelConnectivity.READY.
1737 from grpc import _utilities # pylint: disable=cyclic-import
1738 return _utilities.channel_ready_future(channel)
1741 def insecure_channel(target, options=None, compression=None):
1742 """Creates an insecure Channel to a server.
1744 The returned Channel is thread-safe.
1747 target: The server address
1748 options: An optional list of key-value pairs (channel args
1749 in gRPC Core runtime) to configure the channel.
1750 compression: An optional value indicating the compression method to be
1751 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1756 from grpc import _channel # pylint: disable=cyclic-import
1757 return _channel.Channel(target, ()
1758 if options is None else options, None, compression)
1761 def secure_channel(target, credentials, options=None, compression=None):
1762 """Creates a secure Channel to a server.
1764 The returned Channel is thread-safe.
1767 target: The server address.
1768 credentials: A ChannelCredentials instance.
1769 options: An optional list of key-value pairs (channel args
1770 in gRPC Core runtime) to configure the channel.
1771 compression: An optional value indicating the compression method to be
1772 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1777 from grpc import _channel # pylint: disable=cyclic-import
1778 return _channel.Channel(target, () if options is None else options,
1779 credentials._credentials, compression)
1782 def intercept_channel(channel, *interceptors):
1783 """Intercepts a channel through a set of interceptors.
1785 This is an EXPERIMENTAL API.
1789 interceptors: Zero or more objects of type
1790 UnaryUnaryClientInterceptor,
1791 UnaryStreamClientInterceptor,
1792 StreamUnaryClientInterceptor, or
1793 StreamStreamClientInterceptor.
1794 Interceptors are given control in the order they are listed.
1797 A Channel that intercepts each invocation via the provided interceptors.
1800 TypeError: If interceptor does not derive from any of
1801 UnaryUnaryClientInterceptor,
1802 UnaryStreamClientInterceptor,
1803 StreamUnaryClientInterceptor, or
1804 StreamStreamClientInterceptor.
1806 from grpc import _interceptor # pylint: disable=cyclic-import
1807 return _interceptor.intercept_channel(channel, *interceptors)
1810 def server(thread_pool,
1814 maximum_concurrent_rpcs=None,
1816 """Creates a Server with which RPCs can be serviced.
1819 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
1820 to execute RPC handlers.
1821 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
1822 More handlers may be added by calling add_generic_rpc_handlers any time
1823 before the server is started.
1824 interceptors: An optional list of ServerInterceptor objects that observe
1825 and optionally manipulate the incoming RPCs before handing them over to
1826 handlers. The interceptors are given control in the order they are
1827 specified. This is an EXPERIMENTAL API.
1828 options: An optional list of key-value pairs (channel args in gRPC runtime)
1829 to configure the channel.
1830 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
1831 will service before returning RESOURCE_EXHAUSTED status, or None to
1833 compression: An element of grpc.compression, e.g.
1834 grpc.compression.Gzip. This compression algorithm will be used for the
1835 lifetime of the server unless overridden. This is an EXPERIMENTAL option.
1840 from grpc import _server # pylint: disable=cyclic-import
1841 return _server.create_server(thread_pool, ()
1842 if handlers is None else handlers, ()
1843 if interceptors is None else interceptors, ()
1844 if options is None else options,
1845 maximum_concurrent_rpcs, compression)
1848 @contextlib.contextmanager
1849 def _create_servicer_context(rpc_event, state, request_deserializer):
1850 from grpc import _server # pylint: disable=cyclic-import
1851 context = _server._Context(rpc_event, state, request_deserializer)
1853 context._finalize_state() # pylint: disable=protected-access
1857 class Compression(enum.IntEnum):
1858 """Indicates the compression method to be used for an RPC.
1860 This enumeration is part of an EXPERIMENTAL API.
1863 NoCompression: Do not use compression algorithm.
1864 Deflate: Use "Deflate" compression algorithm.
1865 Gzip: Use "Gzip" compression algorithm.
1867 NoCompression = _compression.NoCompression
1868 Deflate = _compression.Deflate
1869 Gzip = _compression.Gzip
1872 ################################### __all__ #################################
1875 'FutureTimeoutError',
1876 'FutureCancelledError',
1878 'ChannelConnectivity',
1884 'ChannelCredentials',
1886 'AuthMetadataContext',
1887 'AuthMetadataPluginCallback',
1888 'AuthMetadataPlugin',
1890 'ClientCallDetails',
1891 'ServerCertificateConfiguration',
1892 'ServerCredentials',
1893 'UnaryUnaryMultiCallable',
1894 'UnaryStreamMultiCallable',
1895 'StreamUnaryMultiCallable',
1896 'StreamStreamMultiCallable',
1897 'UnaryUnaryClientInterceptor',
1898 'UnaryStreamClientInterceptor',
1899 'StreamUnaryClientInterceptor',
1900 'StreamStreamClientInterceptor',
1904 'HandlerCallDetails',
1905 'GenericRpcHandler',
1906 'ServiceRpcHandler',
1908 'ServerInterceptor',
1909 'unary_unary_rpc_method_handler',
1910 'unary_stream_rpc_method_handler',
1911 'stream_unary_rpc_method_handler',
1912 'stream_stream_rpc_method_handler',
1913 'method_handlers_generic_handler',
1914 'ssl_channel_credentials',
1915 'metadata_call_credentials',
1916 'access_token_call_credentials',
1917 'composite_call_credentials',
1918 'composite_channel_credentials',
1919 'ssl_server_credentials',
1920 'ssl_server_certificate_configuration',
1921 'dynamic_ssl_server_credentials',
1922 'channel_ready_future',
1925 'intercept_channel',
1929 ############################### Extension Shims ################################
1931 # Here to maintain backwards compatibility; avoid using these in new code!
1934 sys.modules.update({'grpc.tools': grpc_tools})
1939 sys.modules.update({'grpc.health': grpc_health})
1943 import grpc_reflection
1944 sys.modules.update({'grpc.reflection': grpc_reflection})