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 may be composed with ChannelCredentials to always assert
588 identity for every call over that Channel.
590 This class has no supported interface - it exists to define the type of its
591 instances and its instances exist to be passed to other functions.
594 def __init__(self, credentials):
595 self._credentials = credentials
598 class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
599 """Provides information to call credentials metadata plugins.
602 service_url: A string URL of the service being called into.
603 method_name: A string of the fully qualified method name being called.
607 class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
608 """Callback object received by a metadata plugin."""
610 def __call__(self, metadata, error):
611 """Passes to the gRPC runtime authentication metadata for an RPC.
614 metadata: The :term:`metadata` used to construct the CallCredentials.
615 error: An Exception to indicate error or None to indicate success.
617 raise NotImplementedError()
620 class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
621 """A specification for custom authentication."""
623 def __call__(self, context, callback):
624 """Implements authentication by passing metadata to a callback.
626 Implementations of this method must not block.
629 context: An AuthMetadataContext providing information on the RPC that
630 the plugin is being called to authenticate.
631 callback: An AuthMetadataPluginCallback to be invoked either
632 synchronously or asynchronously.
634 raise NotImplementedError()
637 class ServerCredentials(object):
638 """An encapsulation of the data required to open a secure port on a Server.
640 This class has no supported interface - it exists to define the type of its
641 instances and its instances exist to be passed to other functions.
644 def __init__(self, credentials):
645 self._credentials = credentials
648 class ServerCertificateConfiguration(object):
649 """A certificate configuration for use with an SSL-enabled Server.
651 Instances of this class can be returned in the certificate configuration
654 This class has no supported interface -- it exists to define the
655 type of its instances and its instances exist to be passed to
659 def __init__(self, certificate_configuration):
660 self._certificate_configuration = certificate_configuration
663 ######################## Multi-Callable Interfaces ###########################
666 class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
667 """Affords invoking a unary-unary RPC from client-side."""
677 """Synchronously invokes the underlying RPC.
680 request: The request value for the RPC.
681 timeout: An optional duration of time in seconds to allow
683 metadata: Optional :term:`metadata` to be transmitted to the
684 service-side of the RPC.
685 credentials: An optional CallCredentials for the RPC.
686 wait_for_ready: This is an EXPERIMENTAL argument. An optional
687 flag to enable wait for ready mechanism
688 compression: An element of grpc.compression, e.g.
689 grpc.compression.Gzip. This is an EXPERIMENTAL option.
692 The response value for the RPC.
695 RpcError: Indicating that the RPC terminated with non-OK status. The
696 raised RpcError will also be a Call for the RPC affording the RPC's
697 metadata, status code, and details.
699 raise NotImplementedError()
709 """Synchronously invokes the underlying RPC.
712 request: The request value for the RPC.
713 timeout: An optional durating of time in seconds to allow for
715 metadata: Optional :term:`metadata` to be transmitted to the
716 service-side of the RPC.
717 credentials: An optional CallCredentials for the RPC.
718 wait_for_ready: This is an EXPERIMENTAL argument. An optional
719 flag to enable wait for ready mechanism
720 compression: An element of grpc.compression, e.g.
721 grpc.compression.Gzip. This is an EXPERIMENTAL option.
724 The response value for the RPC and a Call value for the RPC.
727 RpcError: Indicating that the RPC terminated with non-OK status. The
728 raised RpcError will also be a Call for the RPC affording the RPC's
729 metadata, status code, and details.
731 raise NotImplementedError()
741 """Asynchronously invokes the underlying RPC.
744 request: The request value for the RPC.
745 timeout: An optional duration of time in seconds to allow for
747 metadata: Optional :term:`metadata` to be transmitted to the
748 service-side of the RPC.
749 credentials: An optional CallCredentials for the RPC.
750 wait_for_ready: This is an EXPERIMENTAL argument. An optional
751 flag to enable wait for ready mechanism
752 compression: An element of grpc.compression, e.g.
753 grpc.compression.Gzip. This is an EXPERIMENTAL option.
756 An object that is both a Call for the RPC and a Future.
757 In the event of RPC completion, the return Call-Future's result
758 value will be the response message of the RPC.
759 Should the event terminate with non-OK status,
760 the returned Call-Future's exception value will be an RpcError.
762 raise NotImplementedError()
765 class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
766 """Affords invoking a unary-stream RPC from client-side."""
776 """Invokes the underlying RPC.
779 request: The request value for the RPC.
780 timeout: An optional duration of time in seconds to allow for
781 the RPC. If None, the timeout is considered infinite.
782 metadata: An optional :term:`metadata` to be transmitted to the
783 service-side of the RPC.
784 credentials: An optional CallCredentials for the RPC.
785 wait_for_ready: This is an EXPERIMENTAL argument. An optional
786 flag to enable wait for ready mechanism
787 compression: An element of grpc.compression, e.g.
788 grpc.compression.Gzip. This is an EXPERIMENTAL option.
791 An object that is both a Call for the RPC and an iterator of
792 response values. Drawing response values from the returned
793 Call-iterator may raise RpcError indicating termination of the
794 RPC with non-OK status.
796 raise NotImplementedError()
799 class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
800 """Affords invoking a stream-unary RPC from client-side."""
810 """Synchronously invokes the underlying RPC.
813 request_iterator: An iterator that yields request values for
815 timeout: An optional duration of time in seconds to allow for
816 the RPC. If None, the timeout is considered infinite.
817 metadata: Optional :term:`metadata` to be transmitted to the
818 service-side of the RPC.
819 credentials: An optional CallCredentials for the RPC.
820 wait_for_ready: This is an EXPERIMENTAL argument. An optional
821 flag to enable wait for ready mechanism
822 compression: An element of grpc.compression, e.g.
823 grpc.compression.Gzip. This is an EXPERIMENTAL option.
826 The response value for the RPC.
829 RpcError: Indicating that the RPC terminated with non-OK status. The
830 raised RpcError will also implement grpc.Call, affording methods
831 such as metadata, code, and details.
833 raise NotImplementedError()
843 """Synchronously invokes the underlying RPC on the client.
846 request_iterator: An iterator that yields request values for
848 timeout: An optional duration of time in seconds to allow for
849 the RPC. If None, the timeout is considered infinite.
850 metadata: Optional :term:`metadata` to be transmitted to the
851 service-side of the RPC.
852 credentials: An optional CallCredentials for the RPC.
853 wait_for_ready: This is an EXPERIMENTAL argument. An optional
854 flag to enable wait for ready mechanism
855 compression: An element of grpc.compression, e.g.
856 grpc.compression.Gzip. This is an EXPERIMENTAL option.
859 The response value for the RPC and a Call object for the RPC.
862 RpcError: Indicating that the RPC terminated with non-OK status. The
863 raised RpcError will also be a Call for the RPC affording the RPC's
864 metadata, status code, and details.
866 raise NotImplementedError()
876 """Asynchronously invokes the underlying RPC on the client.
879 request_iterator: An iterator that yields request values for the RPC.
880 timeout: An optional duration of time in seconds to allow for
881 the RPC. If None, the timeout is considered infinite.
882 metadata: Optional :term:`metadata` to be transmitted to the
883 service-side of the RPC.
884 credentials: An optional CallCredentials for the RPC.
885 wait_for_ready: This is an EXPERIMENTAL argument. An optional
886 flag to enable wait for ready mechanism
887 compression: An element of grpc.compression, e.g.
888 grpc.compression.Gzip. This is an EXPERIMENTAL option.
891 An object that is both a Call for the RPC and a Future.
892 In the event of RPC completion, the return Call-Future's result value
893 will be the response message of the RPC. Should the event terminate
894 with non-OK status, the returned Call-Future's exception value will
897 raise NotImplementedError()
900 class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
901 """Affords invoking a stream-stream RPC on client-side."""
911 """Invokes the underlying RPC on the client.
914 request_iterator: An iterator that yields request values for the RPC.
915 timeout: An optional duration of time in seconds to allow for
916 the RPC. If not specified, the timeout is considered infinite.
917 metadata: Optional :term:`metadata` to be transmitted to the
918 service-side of the RPC.
919 credentials: An optional CallCredentials for the RPC.
920 wait_for_ready: This is an EXPERIMENTAL argument. An optional
921 flag to enable wait for ready mechanism
922 compression: An element of grpc.compression, e.g.
923 grpc.compression.Gzip. This is an EXPERIMENTAL option.
926 An object that is both a Call for the RPC and an iterator of
927 response values. Drawing response values from the returned
928 Call-iterator may raise RpcError indicating termination of the
929 RPC with non-OK status.
931 raise NotImplementedError()
934 ############################# Channel Interface ##############################
937 class Channel(six.with_metaclass(abc.ABCMeta)):
938 """Affords RPC invocation via generic methods on client-side.
940 Channel objects implement the Context Manager type, although they need not
941 support being entered and exited multiple times.
945 def subscribe(self, callback, try_to_connect=False):
946 """Subscribe to this Channel's connectivity state machine.
948 A Channel may be in any of the states described by ChannelConnectivity.
949 This method allows application to monitor the state transitions.
950 The typical use case is to debug or gain better visibility into gRPC
954 callback: A callable to be invoked with ChannelConnectivity argument.
955 ChannelConnectivity describes current state of the channel.
956 The callable will be invoked immediately upon subscription
957 and again for every change to ChannelConnectivity until it
958 is unsubscribed or this Channel object goes out of scope.
959 try_to_connect: A boolean indicating whether or not this Channel
960 should attempt to connect immediately. If set to False, gRPC
961 runtime decides when to connect.
963 raise NotImplementedError()
966 def unsubscribe(self, callback):
967 """Unsubscribes a subscribed callback from this Channel's connectivity.
970 callback: A callable previously registered with this Channel from
971 having been passed to its "subscribe" method.
973 raise NotImplementedError()
976 def unary_unary(self,
978 request_serializer=None,
979 response_deserializer=None):
980 """Creates a UnaryUnaryMultiCallable for a unary-unary method.
983 method: The name of the RPC method.
984 request_serializer: Optional behaviour for serializing the request
985 message. Request goes unserialized in case None is passed.
986 response_deserializer: Optional behaviour for deserializing the
987 response message. Response goes undeserialized in case None
991 A UnaryUnaryMultiCallable value for the named unary-unary method.
993 raise NotImplementedError()
996 def unary_stream(self,
998 request_serializer=None,
999 response_deserializer=None):
1000 """Creates a UnaryStreamMultiCallable for a unary-stream method.
1003 method: The name of the RPC method.
1004 request_serializer: Optional behaviour for serializing the request
1005 message. Request goes unserialized in case None is passed.
1006 response_deserializer: Optional behaviour for deserializing the
1007 response message. Response goes undeserialized in case None is
1011 A UnaryStreamMultiCallable value for the name unary-stream method.
1013 raise NotImplementedError()
1016 def stream_unary(self,
1018 request_serializer=None,
1019 response_deserializer=None):
1020 """Creates a StreamUnaryMultiCallable for a stream-unary method.
1023 method: The name of the RPC method.
1024 request_serializer: Optional behaviour for serializing the request
1025 message. Request goes unserialized in case None is passed.
1026 response_deserializer: Optional behaviour for deserializing the
1027 response message. Response goes undeserialized in case None is
1031 A StreamUnaryMultiCallable value for the named stream-unary method.
1033 raise NotImplementedError()
1036 def stream_stream(self,
1038 request_serializer=None,
1039 response_deserializer=None):
1040 """Creates a StreamStreamMultiCallable for a stream-stream method.
1043 method: The name of the RPC method.
1044 request_serializer: Optional behaviour for serializing the request
1045 message. Request goes unserialized in case None is passed.
1046 response_deserializer: Optional behaviour for deserializing the
1047 response message. Response goes undeserialized in case None
1051 A StreamStreamMultiCallable value for the named stream-stream method.
1053 raise NotImplementedError()
1057 """Closes this Channel and releases all resources held by it.
1059 Closing the Channel will immediately terminate all RPCs active with the
1060 Channel and it is not valid to invoke new RPCs with the Channel.
1062 This method is idempotent.
1064 raise NotImplementedError()
1067 ########################## Service-Side Context ##############################
1070 class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
1071 """A context object passed to method implementations."""
1074 def invocation_metadata(self):
1075 """Accesses the metadata from the sent by the client.
1078 The invocation :term:`metadata`.
1080 raise NotImplementedError()
1084 """Identifies the peer that invoked the RPC being serviced.
1087 A string identifying the peer that invoked the RPC being serviced.
1088 The string format is determined by gRPC runtime.
1090 raise NotImplementedError()
1093 def peer_identities(self):
1094 """Gets one or more peer identity(s).
1097 servicer_context.auth_context().get(servicer_context.peer_identity_key())
1100 An iterable of the identities, or None if the call is not
1101 authenticated. Each identity is returned as a raw bytes type.
1103 raise NotImplementedError()
1106 def peer_identity_key(self):
1107 """The auth property used to identify the peer.
1109 For example, "x509_common_name" or "x509_subject_alternative_name" are
1110 used to identify an SSL peer.
1113 The auth property (string) that indicates the
1114 peer identity, or None if the call is not authenticated.
1116 raise NotImplementedError()
1119 def auth_context(self):
1120 """Gets the auth context for the call.
1123 A map of strings to an iterable of bytes for each auth property.
1125 raise NotImplementedError()
1127 def set_compression(self, compression):
1128 """Set the compression algorithm to be used for the entire call.
1130 This is an EXPERIMENTAL method.
1133 compression: An element of grpc.compression, e.g.
1134 grpc.compression.Gzip.
1136 raise NotImplementedError()
1139 def send_initial_metadata(self, initial_metadata):
1140 """Sends the initial metadata value to the client.
1142 This method need not be called by implementations if they have no
1143 metadata to add to what the gRPC runtime will transmit.
1146 initial_metadata: The initial :term:`metadata`.
1148 raise NotImplementedError()
1151 def set_trailing_metadata(self, trailing_metadata):
1152 """Sends the trailing metadata for the RPC.
1154 This method need not be called by implementations if they have no
1155 metadata to add to what the gRPC runtime will transmit.
1158 trailing_metadata: The trailing :term:`metadata`.
1160 raise NotImplementedError()
1163 def abort(self, code, details):
1164 """Raises an exception to terminate the RPC with a non-OK status.
1166 The code and details passed as arguments will supercede any existing
1170 code: A StatusCode object to be sent to the client.
1171 It must not be StatusCode.OK.
1172 details: A UTF-8-encodable string to be sent to the client upon
1173 termination of the RPC.
1176 Exception: An exception is always raised to signal the abortion the
1177 RPC to the gRPC runtime.
1179 raise NotImplementedError()
1182 def abort_with_status(self, status):
1183 """Raises an exception to terminate the RPC with a non-OK status.
1185 The status passed as argument will supercede any existing status code,
1186 status message and trailing metadata.
1188 This is an EXPERIMENTAL API.
1191 status: A grpc.Status object. The status code in it must not be
1195 Exception: An exception is always raised to signal the abortion the
1196 RPC to the gRPC runtime.
1198 raise NotImplementedError()
1201 def set_code(self, code):
1202 """Sets the value to be used as status code upon RPC completion.
1204 This method need not be called by method implementations if they wish
1205 the gRPC runtime to determine the status code of the RPC.
1208 code: A StatusCode object to be sent to the client.
1210 raise NotImplementedError()
1213 def set_details(self, details):
1214 """Sets the value to be used as detail string upon RPC completion.
1216 This method need not be called by method implementations if they have
1217 no details to transmit.
1220 details: A UTF-8-encodable string to be sent to the client upon
1221 termination of the RPC.
1223 raise NotImplementedError()
1225 def disable_next_message_compression(self):
1226 """Disables compression for the next response message.
1228 This is an EXPERIMENTAL method.
1230 This method will override any compression configuration set during
1231 server creation or set on the call.
1233 raise NotImplementedError()
1236 ##################### Service-Side Handler Interfaces ########################
1239 class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
1240 """An implementation of a single RPC method.
1243 request_streaming: Whether the RPC supports exactly one request message
1244 or any arbitrary number of request messages.
1245 response_streaming: Whether the RPC supports exactly one response message
1246 or any arbitrary number of response messages.
1247 request_deserializer: A callable behavior that accepts a byte string and
1248 returns an object suitable to be passed to this object's business
1249 logic, or None to indicate that this object's business logic should be
1250 passed the raw request bytes.
1251 response_serializer: A callable behavior that accepts an object produced
1252 by this object's business logic and returns a byte string, or None to
1253 indicate that the byte strings produced by this object's business logic
1254 should be transmitted on the wire as they are.
1255 unary_unary: This object's application-specific business logic as a
1256 callable value that takes a request value and a ServicerContext object
1257 and returns a response value. Only non-None if both request_streaming
1258 and response_streaming are False.
1259 unary_stream: This object's application-specific business logic as a
1260 callable value that takes a request value and a ServicerContext object
1261 and returns an iterator of response values. Only non-None if
1262 request_streaming is False and response_streaming is True.
1263 stream_unary: This object's application-specific business logic as a
1264 callable value that takes an iterator of request values and a
1265 ServicerContext object and returns a response value. Only non-None if
1266 request_streaming is True and response_streaming is False.
1267 stream_stream: This object's application-specific business logic as a
1268 callable value that takes an iterator of request values and a
1269 ServicerContext object and returns an iterator of response values.
1270 Only non-None if request_streaming and response_streaming are both
1275 class HandlerCallDetails(six.with_metaclass(abc.ABCMeta)):
1276 """Describes an RPC that has just arrived for service.
1278 method: The method name of the RPC.
1279 invocation_metadata: The :term:`metadata` sent by the client.
1283 class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
1284 """An implementation of arbitrarily many RPC methods."""
1287 def service(self, handler_call_details):
1288 """Returns the handler for servicing the RPC.
1291 handler_call_details: A HandlerCallDetails describing the RPC.
1294 An RpcMethodHandler with which the RPC may be serviced if the
1295 implementation chooses to service this RPC, or None otherwise.
1297 raise NotImplementedError()
1300 class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
1301 """An implementation of RPC methods belonging to a service.
1303 A service handles RPC methods with structured names of the form
1304 '/Service.Name/Service.Method', where 'Service.Name' is the value
1305 returned by service_name(), and 'Service.Method' is the method
1306 name. A service can have multiple method names, but only a single
1311 def service_name(self):
1312 """Returns this service's name.
1317 raise NotImplementedError()
1320 #################### Service-Side Interceptor Interfaces #####################
1323 class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
1324 """Affords intercepting incoming RPCs on the service-side.
1326 This is an EXPERIMENTAL API.
1330 def intercept_service(self, continuation, handler_call_details):
1331 """Intercepts incoming RPCs before handing them over to a handler.
1334 continuation: A function that takes a HandlerCallDetails and
1335 proceeds to invoke the next interceptor in the chain, if any,
1336 or the RPC handler lookup logic, with the call details passed
1337 as an argument, and returns an RpcMethodHandler instance if
1338 the RPC is considered serviced, or None otherwise.
1339 handler_call_details: A HandlerCallDetails describing the RPC.
1342 An RpcMethodHandler with which the RPC may be serviced if the
1343 interceptor chooses to service this RPC, or None otherwise.
1345 raise NotImplementedError()
1348 ############################# Server Interface ###############################
1351 class Server(six.with_metaclass(abc.ABCMeta)):
1352 """Services RPCs."""
1355 def add_generic_rpc_handlers(self, generic_rpc_handlers):
1356 """Registers GenericRpcHandlers with this Server.
1358 This method is only safe to call before the server is started.
1361 generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
1362 used to service RPCs.
1364 raise NotImplementedError()
1367 def add_insecure_port(self, address):
1368 """Opens an insecure port for accepting RPCs.
1370 This method may only be called before starting the server.
1373 address: The address for which to open a port.
1374 if the port is 0, or not specified in the address, then gRPC runtime
1379 An integer port on which server will accept RPC requests.
1381 raise NotImplementedError()
1384 def add_secure_port(self, address, server_credentials):
1385 """Opens a secure port for accepting RPCs.
1387 This method may only be called before starting the server.
1390 address: The address for which to open a port.
1391 if the port is 0, or not specified in the address, then gRPC
1392 runtime will choose a port.
1393 server_credentials: A ServerCredentials object.
1397 An integer port on which server will accept RPC requests.
1399 raise NotImplementedError()
1403 """Starts this Server.
1405 This method may only be called once. (i.e. it is not idempotent).
1407 raise NotImplementedError()
1410 def stop(self, grace):
1411 """Stops this Server.
1413 This method immediately stop service of new RPCs in all cases.
1415 If a grace period is specified, this method returns immediately
1416 and all RPCs active at the end of the grace period are aborted.
1417 If a grace period is not specified (by passing None for `grace`),
1418 all existing RPCs are aborted immediately and this method
1419 blocks until the last RPC handler terminates.
1421 This method is idempotent and may be called at any time.
1422 Passing a smaller grace value in a subsequent call will have
1423 the effect of stopping the Server sooner (passing None will
1424 have the effect of stopping the server immediately). Passing
1425 a larger grace value in a subsequent call *will not* have the
1426 effect of stopping the server later (i.e. the most restrictive
1427 grace value is used).
1430 grace: A duration of time in seconds or None.
1433 A threading.Event that will be set when this Server has completely
1434 stopped, i.e. when running RPCs either complete or are aborted and
1435 all handlers have terminated.
1437 raise NotImplementedError()
1440 ################################# Functions ################################
1443 def unary_unary_rpc_method_handler(behavior,
1444 request_deserializer=None,
1445 response_serializer=None):
1446 """Creates an RpcMethodHandler for a unary-unary RPC method.
1449 behavior: The implementation of an RPC that accepts one request
1450 and returns one response.
1451 request_deserializer: An optional behavior for request deserialization.
1452 response_serializer: An optional behavior for response serialization.
1455 An RpcMethodHandler object that is typically used by grpc.Server.
1457 from grpc import _utilities # pylint: disable=cyclic-import
1458 return _utilities.RpcMethodHandler(False, False, request_deserializer,
1459 response_serializer, behavior, None,
1463 def unary_stream_rpc_method_handler(behavior,
1464 request_deserializer=None,
1465 response_serializer=None):
1466 """Creates an RpcMethodHandler for a unary-stream RPC method.
1469 behavior: The implementation of an RPC that accepts one request
1470 and returns an iterator of response values.
1471 request_deserializer: An optional behavior for request deserialization.
1472 response_serializer: An optional behavior for response serialization.
1475 An RpcMethodHandler object that is typically used by grpc.Server.
1477 from grpc import _utilities # pylint: disable=cyclic-import
1478 return _utilities.RpcMethodHandler(False, True, request_deserializer,
1479 response_serializer, None, behavior,
1483 def stream_unary_rpc_method_handler(behavior,
1484 request_deserializer=None,
1485 response_serializer=None):
1486 """Creates an RpcMethodHandler for a stream-unary RPC method.
1489 behavior: The implementation of an RPC that accepts an iterator of
1490 request values and returns a single response value.
1491 request_deserializer: An optional behavior for request deserialization.
1492 response_serializer: An optional behavior for response serialization.
1495 An RpcMethodHandler object that is typically used by grpc.Server.
1497 from grpc import _utilities # pylint: disable=cyclic-import
1498 return _utilities.RpcMethodHandler(True, False, request_deserializer,
1499 response_serializer, None, None,
1503 def stream_stream_rpc_method_handler(behavior,
1504 request_deserializer=None,
1505 response_serializer=None):
1506 """Creates an RpcMethodHandler for a stream-stream RPC method.
1509 behavior: The implementation of an RPC that accepts an iterator of
1510 request values and returns an iterator of response values.
1511 request_deserializer: An optional behavior for request deserialization.
1512 response_serializer: An optional behavior for response serialization.
1515 An RpcMethodHandler object that is typically used by grpc.Server.
1517 from grpc import _utilities # pylint: disable=cyclic-import
1518 return _utilities.RpcMethodHandler(True, True, request_deserializer,
1519 response_serializer, None, None, None,
1523 def method_handlers_generic_handler(service, method_handlers):
1524 """Creates a GenericRpcHandler from RpcMethodHandlers.
1527 service: The name of the service that is implemented by the
1529 method_handlers: A dictionary that maps method names to corresponding
1533 A GenericRpcHandler. This is typically added to the grpc.Server object
1534 with add_generic_rpc_handlers() before starting the server.
1536 from grpc import _utilities # pylint: disable=cyclic-import
1537 return _utilities.DictionaryGenericHandler(service, method_handlers)
1540 def ssl_channel_credentials(root_certificates=None,
1542 certificate_chain=None):
1543 """Creates a ChannelCredentials for use with an SSL-enabled Channel.
1546 root_certificates: The PEM-encoded root certificates as a byte string,
1547 or None to retrieve them from a default location chosen by gRPC
1549 private_key: The PEM-encoded private key as a byte string, or None if no
1550 private key should be used.
1551 certificate_chain: The PEM-encoded certificate chain as a byte string
1552 to use or or None if no certificate chain should be used.
1555 A ChannelCredentials for use with an SSL-enabled Channel.
1557 return ChannelCredentials(
1558 _cygrpc.SSLChannelCredentials(root_certificates, private_key,
1562 def metadata_call_credentials(metadata_plugin, name=None):
1563 """Construct CallCredentials from an AuthMetadataPlugin.
1566 metadata_plugin: An AuthMetadataPlugin to use for authentication.
1567 name: An optional name for the plugin.
1572 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1573 return _plugin_wrapping.metadata_plugin_call_credentials(
1574 metadata_plugin, name)
1577 def access_token_call_credentials(access_token):
1578 """Construct CallCredentials from an access token.
1581 access_token: A string to place directly in the http request
1582 authorization header, for example
1583 "authorization: Bearer <access_token>".
1588 from grpc import _auth # pylint: disable=cyclic-import
1589 from grpc import _plugin_wrapping # pylint: disable=cyclic-import
1590 return _plugin_wrapping.metadata_plugin_call_credentials(
1591 _auth.AccessTokenAuthMetadataPlugin(access_token), None)
1594 def composite_call_credentials(*call_credentials):
1595 """Compose multiple CallCredentials to make a new CallCredentials.
1598 *call_credentials: At least two CallCredentials objects.
1601 A CallCredentials object composed of the given CallCredentials objects.
1603 return CallCredentials(
1604 _cygrpc.CompositeCallCredentials(
1605 tuple(single_call_credentials._credentials
1606 for single_call_credentials in call_credentials)))
1609 def composite_channel_credentials(channel_credentials, *call_credentials):
1610 """Compose a ChannelCredentials and one or more CallCredentials objects.
1613 channel_credentials: A ChannelCredentials object.
1614 *call_credentials: One or more CallCredentials objects.
1617 A ChannelCredentials composed of the given ChannelCredentials and
1618 CallCredentials objects.
1620 return ChannelCredentials(
1621 _cygrpc.CompositeChannelCredentials(
1622 tuple(single_call_credentials._credentials
1623 for single_call_credentials in call_credentials),
1624 channel_credentials._credentials))
1627 def ssl_server_credentials(private_key_certificate_chain_pairs,
1628 root_certificates=None,
1629 require_client_auth=False):
1630 """Creates a ServerCredentials for use with an SSL-enabled Server.
1633 private_key_certificate_chain_pairs: A list of pairs of the form
1634 [PEM-encoded private key, PEM-encoded certificate chain].
1635 root_certificates: An optional byte string of PEM-encoded client root
1636 certificates that the server will use to verify client authentication.
1637 If omitted, require_client_auth must also be False.
1638 require_client_auth: A boolean indicating whether or not to require
1639 clients to be authenticated. May only be True if root_certificates
1643 A ServerCredentials for use with an SSL-enabled Server. Typically, this
1644 object is an argument to add_secure_port() method during server setup.
1646 if not private_key_certificate_chain_pairs:
1648 'At least one private key-certificate chain pair is required!')
1649 elif require_client_auth and root_certificates is None:
1651 'Illegal to require client auth without providing root certificates!'
1654 return ServerCredentials(
1655 _cygrpc.server_credentials_ssl(root_certificates, [
1656 _cygrpc.SslPemKeyCertPair(key, pem)
1657 for key, pem in private_key_certificate_chain_pairs
1658 ], require_client_auth))
1661 def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
1662 root_certificates=None):
1663 """Creates a ServerCertificateConfiguration for use with a Server.
1666 private_key_certificate_chain_pairs: A collection of pairs of
1667 the form [PEM-encoded private key, PEM-encoded certificate
1669 root_certificates: An optional byte string of PEM-encoded client root
1670 certificates that the server will use to verify client authentication.
1673 A ServerCertificateConfiguration that can be returned in the certificate
1674 configuration fetching callback.
1676 if private_key_certificate_chain_pairs:
1677 return ServerCertificateConfiguration(
1678 _cygrpc.server_certificate_config_ssl(root_certificates, [
1679 _cygrpc.SslPemKeyCertPair(key, pem)
1680 for key, pem in private_key_certificate_chain_pairs
1684 'At least one private key-certificate chain pair is required!')
1687 def dynamic_ssl_server_credentials(initial_certificate_configuration,
1688 certificate_configuration_fetcher,
1689 require_client_authentication=False):
1690 """Creates a ServerCredentials for use with an SSL-enabled Server.
1693 initial_certificate_configuration (ServerCertificateConfiguration): The
1694 certificate configuration with which the server will be initialized.
1695 certificate_configuration_fetcher (callable): A callable that takes no
1696 arguments and should return a ServerCertificateConfiguration to
1697 replace the server's current certificate, or None for no change
1698 (i.e., the server will continue its current certificate
1699 config). The library will call this callback on *every* new
1700 client connection before starting the TLS handshake with the
1701 client, thus allowing the user application to optionally
1702 return a new ServerCertificateConfiguration that the server will then
1703 use for the handshake.
1704 require_client_authentication: A boolean indicating whether or not to
1705 require clients to be authenticated.
1708 A ServerCredentials.
1710 return ServerCredentials(
1711 _cygrpc.server_credentials_ssl_dynamic_cert_config(
1712 initial_certificate_configuration,
1713 certificate_configuration_fetcher, require_client_authentication))
1716 def channel_ready_future(channel):
1717 """Creates a Future that tracks when a Channel is ready.
1719 Cancelling the Future does not affect the channel's state machine.
1720 It merely decouples the Future from channel state machine.
1723 channel: A Channel object.
1726 A Future object that matures when the channel connectivity is
1727 ChannelConnectivity.READY.
1729 from grpc import _utilities # pylint: disable=cyclic-import
1730 return _utilities.channel_ready_future(channel)
1733 def insecure_channel(target, options=None, compression=None):
1734 """Creates an insecure Channel to a server.
1736 The returned Channel is thread-safe.
1739 target: The server address
1740 options: An optional list of key-value pairs (channel args
1741 in gRPC Core runtime) to configure the channel.
1742 compression: An optional value indicating the compression method to be
1743 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1748 from grpc import _channel # pylint: disable=cyclic-import
1749 return _channel.Channel(target, ()
1750 if options is None else options, None, compression)
1753 def secure_channel(target, credentials, options=None, compression=None):
1754 """Creates a secure Channel to a server.
1756 The returned Channel is thread-safe.
1759 target: The server address.
1760 credentials: A ChannelCredentials instance.
1761 options: An optional list of key-value pairs (channel args
1762 in gRPC Core runtime) to configure the channel.
1763 compression: An optional value indicating the compression method to be
1764 used over the lifetime of the channel. This is an EXPERIMENTAL option.
1769 from grpc import _channel # pylint: disable=cyclic-import
1770 return _channel.Channel(target, () if options is None else options,
1771 credentials._credentials, compression)
1774 def intercept_channel(channel, *interceptors):
1775 """Intercepts a channel through a set of interceptors.
1777 This is an EXPERIMENTAL API.
1781 interceptors: Zero or more objects of type
1782 UnaryUnaryClientInterceptor,
1783 UnaryStreamClientInterceptor,
1784 StreamUnaryClientInterceptor, or
1785 StreamStreamClientInterceptor.
1786 Interceptors are given control in the order they are listed.
1789 A Channel that intercepts each invocation via the provided interceptors.
1792 TypeError: If interceptor does not derive from any of
1793 UnaryUnaryClientInterceptor,
1794 UnaryStreamClientInterceptor,
1795 StreamUnaryClientInterceptor, or
1796 StreamStreamClientInterceptor.
1798 from grpc import _interceptor # pylint: disable=cyclic-import
1799 return _interceptor.intercept_channel(channel, *interceptors)
1802 def server(thread_pool,
1806 maximum_concurrent_rpcs=None,
1808 """Creates a Server with which RPCs can be serviced.
1811 thread_pool: A futures.ThreadPoolExecutor to be used by the Server
1812 to execute RPC handlers.
1813 handlers: An optional list of GenericRpcHandlers used for executing RPCs.
1814 More handlers may be added by calling add_generic_rpc_handlers any time
1815 before the server is started.
1816 interceptors: An optional list of ServerInterceptor objects that observe
1817 and optionally manipulate the incoming RPCs before handing them over to
1818 handlers. The interceptors are given control in the order they are
1819 specified. This is an EXPERIMENTAL API.
1820 options: An optional list of key-value pairs (channel args in gRPC runtime)
1821 to configure the channel.
1822 maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
1823 will service before returning RESOURCE_EXHAUSTED status, or None to
1825 compression: An element of grpc.compression, e.g.
1826 grpc.compression.Gzip. This compression algorithm will be used for the
1827 lifetime of the server unless overridden. This is an EXPERIMENTAL option.
1832 from grpc import _server # pylint: disable=cyclic-import
1833 return _server.create_server(thread_pool, ()
1834 if handlers is None else handlers, ()
1835 if interceptors is None else interceptors, ()
1836 if options is None else options,
1837 maximum_concurrent_rpcs, compression)
1840 @contextlib.contextmanager
1841 def _create_servicer_context(rpc_event, state, request_deserializer):
1842 from grpc import _server # pylint: disable=cyclic-import
1843 context = _server._Context(rpc_event, state, request_deserializer)
1845 context._finalize_state() # pylint: disable=protected-access
1848 class Compression(enum.IntEnum):
1849 """Indicates the compression method to be used for an RPC.
1851 This enumeration is part of an EXPERIMENTAL API.
1853 NoCompression = _compression.NoCompression
1854 Deflate = _compression.Deflate
1855 Gzip = _compression.Gzip
1858 ################################### __all__ #################################
1861 'FutureTimeoutError',
1862 'FutureCancelledError',
1864 'ChannelConnectivity',
1870 'ChannelCredentials',
1872 'AuthMetadataContext',
1873 'AuthMetadataPluginCallback',
1874 'AuthMetadataPlugin',
1876 'ClientCallDetails',
1877 'ServerCertificateConfiguration',
1878 'ServerCredentials',
1879 'UnaryUnaryMultiCallable',
1880 'UnaryStreamMultiCallable',
1881 'StreamUnaryMultiCallable',
1882 'StreamStreamMultiCallable',
1883 'UnaryUnaryClientInterceptor',
1884 'UnaryStreamClientInterceptor',
1885 'StreamUnaryClientInterceptor',
1886 'StreamStreamClientInterceptor',
1890 'HandlerCallDetails',
1891 'GenericRpcHandler',
1892 'ServiceRpcHandler',
1894 'ServerInterceptor',
1895 'unary_unary_rpc_method_handler',
1896 'unary_stream_rpc_method_handler',
1897 'stream_unary_rpc_method_handler',
1898 'stream_stream_rpc_method_handler',
1899 'method_handlers_generic_handler',
1900 'ssl_channel_credentials',
1901 'metadata_call_credentials',
1902 'access_token_call_credentials',
1903 'composite_call_credentials',
1904 'composite_channel_credentials',
1905 'ssl_server_credentials',
1906 'ssl_server_certificate_configuration',
1907 'dynamic_ssl_server_credentials',
1908 'channel_ready_future',
1911 'intercept_channel',
1915 ############################### Extension Shims ################################
1917 # Here to maintain backwards compatibility; avoid using these in new code!
1920 sys.modules.update({'grpc.tools': grpc_tools})
1925 sys.modules.update({'grpc.health': grpc_health})
1929 import grpc_reflection
1930 sys.modules.update({'grpc.reflection': grpc_reflection})