gRPC AsyncIO API¶
Overview¶
gRPC AsyncIO API is the new version of gRPC Python whose architecture is tailored to AsyncIO. Underlying, it utilizes the same C-extension, gRPC C-Core, as existing stack, and it replaces all gRPC IO operations with methods provided by the AsyncIO library.
This API is stable. Feel free to open issues on our GitHub repo grpc/grpc for bugs or suggestions.
The design doc can be found here as gRFC.
Caveats¶
gRPC Async API objects may only be used on the thread on which they were created. AsyncIO doesn’t provide thread safety for most of its APIs.
Blocking Code in AsyncIO¶
Making blocking function calls in coroutines or in the thread running event loop will block the event loop, potentially starving all RPCs in the process. Refer to the Python language documentation on AsyncIO for more details (running-blocking-code).
Module Contents¶
Create Channel¶
Channels are the abstraction of clients, where most of networking logic happens, for example, managing one or more underlying connections, name resolution, load balancing, flow control, etc.. If you are using ProtoBuf, Channel objects works best when further encapsulate into stub objects, then the application can invoke remote functions as if they are local functions.
- grpc.aio.insecure_channel(target, options=None, compression=None, interceptors=None)[source]¶
Creates an insecure asynchronous Channel to a server.
- Parameters
target (str) – The server address
options (Optional[Sequence[Tuple[str, Any]]]) – An optional list of key-value pairs (channel_arguments in gRPC Core runtime) to configure the channel.
compression (Optional[grpc.Compression]) – An optional value indicating the compression method to be used over the lifetime of the channel. This is an EXPERIMENTAL option.
interceptors (Optional[Sequence[grpc.aio._interceptor.ClientInterceptor]]) – An optional sequence of interceptors that will be executed for any call executed with this channel.
- Returns
A Channel.
- grpc.aio.secure_channel(target, credentials, options=None, compression=None, interceptors=None)[source]¶
Creates a secure asynchronous Channel to a server.
- Parameters
target (str) – The server address.
credentials (grpc.ChannelCredentials) – A ChannelCredentials instance.
options (Optional[Sequence[Tuple[str, Any]]]) – An optional list of key-value pairs (channel_arguments in gRPC Core runtime) to configure the channel.
compression (Optional[grpc.Compression]) – An optional value indicating the compression method to be used over the lifetime of the channel. This is an EXPERIMENTAL option.
interceptors (Optional[Sequence[grpc.aio._interceptor.ClientInterceptor]]) – An optional sequence of interceptors that will be executed for any call executed with this channel.
- Returns
An aio.Channel.
Channel Object¶
- class grpc.aio.Channel[source]¶
Enables asynchronous RPC invocation as a client.
Channel objects implement the Asynchronous Context Manager (aka. async with) type, although they are not supportted to be entered and exited multiple times.
- abstract async __aenter__()[source]¶
Starts an asynchronous context manager.
- Returns
Channel the channel that was instantiated.
- abstract async __aexit__(exc_type, exc_val, exc_tb)[source]¶
Finishes the asynchronous context manager by closing the channel.
Still active RPCs will be cancelled.
- abstract async channel_ready()[source]¶
Creates a coroutine that blocks until the Channel is READY.
- Return type
None
- abstract async close(grace=None)[source]¶
Closes this Channel and releases all resources held by it.
This method immediately stops the channel from executing new RPCs in all cases.
If a grace period is specified, this method wait until all active RPCs are finshed, once the grace period is reached the ones that haven’t been terminated are cancelled. If a grace period is not specified (by passing None for grace), all existing RPCs are cancelled immediately.
This method is idempotent.
- Parameters
grace (Optional[float]) –
- abstract get_state(try_to_connect=False)[source]¶
Checks the connectivity state of a channel.
This is an EXPERIMENTAL API.
If the channel reaches a stable connectivity state, it is guaranteed that the return value of this function will eventually converge to that state.
- Parameters
try_to_connect (bool) – a bool indicate whether the Channel should try to connect to peer or not.
- Return type
Returns: A ChannelConnectivity object.
- abstract stream_stream(method, request_serializer=None, response_deserializer=None)[source]¶
Creates a StreamStreamMultiCallable for a stream-stream method.
- Parameters
method (str) – The name of the RPC method.
request_serializer (Optional[Callable[[Any], bytes]]) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.
response_deserializer (Optional[Callable[[bytes], Any]]) – Optional deserializer for deserializing the response message. Response goes undeserialized in case None is passed.
- Returns
A StreamStreamMultiCallable value for the named stream-stream method.
- Return type
- abstract stream_unary(method, request_serializer=None, response_deserializer=None)[source]¶
Creates a StreamUnaryMultiCallable for a stream-unary method.
- Parameters
method (str) – The name of the RPC method.
request_serializer (Optional[Callable[[Any], bytes]]) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.
response_deserializer (Optional[Callable[[bytes], Any]]) – Optional deserializer for deserializing the response message. Response goes undeserialized in case None is passed.
- Returns
A StreamUnaryMultiCallable value for the named stream-unary method.
- Return type
- abstract unary_stream(method, request_serializer=None, response_deserializer=None)[source]¶
Creates a UnaryStreamMultiCallable for a unary-stream method.
- Parameters
method (str) – The name of the RPC method.
request_serializer (Optional[Callable[[Any], bytes]]) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.
response_deserializer (Optional[Callable[[bytes], Any]]) – Optional deserializer for deserializing the response message. Response goes undeserialized in case None is passed.
- Returns
A UnarySteramMultiCallable value for the named unary-stream method.
- Return type
- abstract unary_unary(method, request_serializer=None, response_deserializer=None)[source]¶
Creates a UnaryUnaryMultiCallable for a unary-unary method.
- Parameters
method (str) – The name of the RPC method.
request_serializer (Optional[Callable[[Any], bytes]]) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.
response_deserializer (Optional[Callable[[bytes], Any]]) – Optional deserializer for deserializing the response message. Response goes undeserialized in case None is passed.
- Returns
A UnaryUnaryMultiCallable value for the named unary-unary method.
- Return type
- abstract async wait_for_state_change(last_observed_state)[source]¶
Waits for a change in connectivity state.
This is an EXPERIMENTAL API.
The function blocks until there is a change in the channel connectivity state from the “last_observed_state”. If the state is already different, this function will return immediately.
There is an inherent race between the invocation of “Channel.wait_for_state_change” and “Channel.get_state”. The state can change arbitrary many times during the race, so there is no way to observe every state transition.
If there is a need to put a timeout for this function, please refer to “asyncio.wait_for”.
- Parameters
last_observed_state (grpc.ChannelConnectivity) – A grpc.ChannelConnectivity object representing the last known state.
- Return type
None
Create Server¶
- grpc.aio.server(migration_thread_pool=None, handlers=None, interceptors=None, options=None, maximum_concurrent_rpcs=None, compression=None)[source]¶
Creates a Server with which RPCs can be serviced.
- Parameters
migration_thread_pool (Optional[concurrent.futures._base.Executor]) – A futures.ThreadPoolExecutor to be used by the Server to execute non-AsyncIO RPC handlers for migration purpose.
handlers (Optional[Sequence[grpc.GenericRpcHandler]]) – An optional list of GenericRpcHandlers used for executing RPCs. More handlers may be added by calling add_generic_rpc_handlers any time before the server is started.
interceptors (Optional[Sequence[Any]]) – An optional list of ServerInterceptor objects that observe and optionally manipulate the incoming RPCs before handing them over to handlers. The interceptors are given control in the order they are specified. This is an EXPERIMENTAL API.
options (Optional[Sequence[Tuple[str, Any]]]) – An optional list of key-value pairs (channel_arguments in gRPC runtime) to configure the channel.
maximum_concurrent_rpcs (Optional[int]) – The maximum number of concurrent RPCs this server will service before returning RESOURCE_EXHAUSTED status, or None to indicate no limit.
compression (Optional[grpc.Compression]) – An element of grpc.compression, e.g. grpc.compression.Gzip. This compression algorithm will be used for the lifetime of the server unless overridden by set_compression. This is an EXPERIMENTAL option.
- Returns
A Server object.
Server Object¶
- class grpc.aio.Server[source]¶
Serves RPCs.
- abstract add_generic_rpc_handlers(generic_rpc_handlers)[source]¶
Registers GenericRpcHandlers with this Server.
This method is only safe to call before the server is started.
- Parameters
generic_rpc_handlers (Sequence[grpc.GenericRpcHandler]) – A sequence of GenericRpcHandlers that will be
RPCs. (used to service) –
- Return type
None
- abstract add_insecure_port(address)[source]¶
Opens an insecure port for accepting RPCs.
A port is a communication endpoint that used by networking protocols, like TCP and UDP. To date, we only support TCP.
This method may only be called before starting the server.
- Parameters
address (str) – The address for which to open a port. If the port is 0, or not specified in the address, then the gRPC runtime will choose a port.
- Returns
An integer port on which the server will accept RPC requests.
- Return type
int
- abstract add_secure_port(address, server_credentials)[source]¶
Opens a secure port for accepting RPCs.
A port is a communication endpoint that used by networking protocols, like TCP and UDP. To date, we only support TCP.
This method may only be called before starting the server.
- Parameters
address (str) – The address for which to open a port. if the port is 0, or not specified in the address, then the gRPC runtime will choose a port.
server_credentials (grpc.ServerCredentials) – A ServerCredentials object.
- Returns
An integer port on which the server will accept RPC requests.
- Return type
int
- abstract async start()[source]¶
Starts this Server.
This method may only be called once. (i.e. it is not idempotent).
- Return type
None
- abstract async stop(grace)[source]¶
Stops this Server.
This method immediately stops the server from servicing new RPCs in all cases.
If a grace period is specified, this method returns immediately and all RPCs active at the end of the grace period are aborted. If a grace period is not specified (by passing None for grace), all existing RPCs are aborted immediately and this method blocks until the last RPC handler terminates.
This method is idempotent and may be called at any time. Passing a smaller grace value in a subsequent call will have the effect of stopping the Server sooner (passing None will have the effect of stopping the server immediately). Passing a larger grace value in a subsequent call will not have the effect of stopping the server later (i.e. the most restrictive grace value is used).
- Parameters
grace (Optional[float]) – A duration of time in seconds or None.
- Return type
None
- abstract async wait_for_termination(timeout=None)[source]¶
Continues current coroutine once the server stops.
This is an EXPERIMENTAL API.
The wait will not consume computational resources during blocking, and it will block until one of the two following conditions are met:
The server is stopped or terminated;
A timeout occurs if timeout is not None.
The timeout argument works in the same way as threading.Event.wait(). https://docs.python.org/3/library/threading.html#threading.Event.wait
- Parameters
timeout (Optional[float]) – A floating point number specifying a timeout for the operation in seconds.
- Returns
A bool indicates if the operation times out.
- Return type
bool
gRPC Exceptions¶
- exception grpc.aio.BaseError¶
The base class for exceptions generated by gRPC AsyncIO stack.
- exception grpc.aio.UsageError¶
Raised when the usage of API by applications is inappropriate.
For example, trying to invoke RPC on a closed channel, mixing two styles of streaming API on the client side. This exception should not be suppressed.
- exception grpc.aio.AbortError¶
Raised when calling abort in servicer methods.
This exception should not be suppressed. Applications may catch it to perform certain clean-up logic, and then re-raise it.
- exception grpc.aio.InternalError¶
Raised upon unexpected errors in native code.
- exception grpc.aio.AioRpcError(code, initial_metadata, trailing_metadata, details=None, debug_error_string=None)[source]¶
An implementation of RpcError to be used by the asynchronous API.
Raised RpcError is a snapshot of the final status of the RPC, values are determined. Hence, its methods no longer needs to be coroutines.
- Parameters
code (grpc.StatusCode) –
initial_metadata (grpc.aio._metadata.Metadata) –
trailing_metadata (grpc.aio._metadata.Metadata) –
details (Optional[str]) –
debug_error_string (Optional[str]) –
- Return type
None
- code()[source]¶
Accesses the status code sent by the server.
- Returns
The grpc.StatusCode status code.
- Return type
- debug_error_string()[source]¶
Accesses the debug error string sent by the server.
- Returns
The debug error string received.
- Return type
str
- details()[source]¶
Accesses the details sent by the server.
- Returns
The description of the error.
- Return type
Optional[str]
- initial_metadata()[source]¶
Accesses the initial metadata sent by the server.
- Returns
The initial metadata received.
- Return type
gRPC Metadata¶
- class grpc.aio.Metadata(*args)[source]¶
Metadata abstraction for the asynchronous calls and interceptors.
The metadata is a mapping from str -> List[str]
- Traits
Multiple entries are allowed for the same key
The order of the values by key is preserved
Getting by an element by key, retrieves the first mapped value
Supports an immutable view of the data
Allows partial mutation on the data without recreating the new object from scratch.
- Parameters
args (Tuple[str, Union[str, bytes]]) –
- Return type
None
- __delitem__(key)[source]¶
del metadata[<key>]
deletes the first mapping for <key>.- Parameters
key (str) –
- Return type
None
- __getitem__(key)[source]¶
When calling <metadata>[<key>], the first element of all those mapped for <key> is returned.
- Parameters
key (str) –
- Return type
Union[str, bytes]
- __len__()[source]¶
Return the total number of elements that there are in the metadata, including multiple values for the same key.
- Return type
int
Client-Side Context¶
- class grpc.aio.Call[source]¶
The abstract base class of an RPC on the client-side.
- abstract async code()[source]¶
Accesses the status code sent by the server.
- Returns
The StatusCode value for the RPC.
- Return type
- abstract async details()[source]¶
Accesses the details sent by the server.
- Returns
The details string of the RPC.
- Return type
str
- abstract async initial_metadata()[source]¶
Accesses the initial metadata sent by the server.
- Returns
The initial metadata.
- Return type
- abstract async trailing_metadata()[source]¶
Accesses the trailing metadata sent by the server.
- Returns
The trailing metadata.
- Return type
- abstract async wait_for_connection()[source]¶
Waits until connected to peer and raises aio.AioRpcError if failed.
This is an EXPERIMENTAL method.
This method ensures the RPC has been successfully connected. Otherwise, an AioRpcError will be raised to explain the reason of the connection failure.
This method is recommended for building retry mechanisms.
- Return type
None
- class grpc.aio.UnaryUnaryCall(*args, **kwds)[source]¶
The abstract base class of an unary-unary RPC on the client-side.
- class grpc.aio.UnaryStreamCall(*args, **kwds)[source]¶
- class grpc.aio.StreamUnaryCall(*args, **kwds)[source]¶
- abstract __await__()[source]¶
Await the response message to be ready.
- Returns
The response message of the stream.
- Return type
Awaitable[grpc.aio._typing.ResponseType]
- class grpc.aio.StreamStreamCall(*args, **kwds)[source]¶
- abstract __aiter__()[source]¶
Returns the async iterable representation that yields messages.
Under the hood, it is calling the “read” method.
- Returns
An async iterable object that yields messages.
- Return type
AsyncIterable[grpc.aio._typing.ResponseType]
- abstract async done_writing()[source]¶
Notifies server that the client is done sending messages.
After done_writing is called, any additional invocation to the write function will fail. This function is idempotent.
- Return type
None
Server-Side Context¶
- class grpc.aio.ServicerContext(*args, **kwds)[source]¶
A context object passed to method implementations.
- abstract async abort(code, details='', trailing_metadata=())[source]¶
Raises an exception to terminate the RPC with a non-OK status.
The code and details passed as arguments will supercede any existing ones.
- Parameters
code (grpc.StatusCode) – A StatusCode object to be sent to the client. It must not be StatusCode.OK.
details (str) – A UTF-8-encodable string to be sent to the client upon termination of the RPC.
trailing_metadata (Union[grpc.aio._metadata.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]) – A sequence of tuple represents the trailing metadata.
- Raises
Exception – An exception is always raised to signal the abortion the RPC to the gRPC runtime.
- Return type
None
- add_done_callback(callback)[source]¶
Registers a callback to be called on RPC termination.
This is an EXPERIMENTAL API.
- Parameters
callback (Callable[[Any], None]) – A callable object will be called with the servicer context object as its only argument.
- Return type
None
- abstract auth_context()[source]¶
Gets the auth context for the call.
- Returns
A map of strings to an iterable of bytes for each auth property.
- Return type
Mapping[str, Iterable[bytes]]
- cancelled()[source]¶
Return True if the RPC is cancelled.
The RPC is cancelled when the cancellation was requested with cancel().
This is an EXPERIMENTAL API.
- Returns
A bool indicates whether the RPC is cancelled or not.
- Return type
bool
- code()[source]¶
Accesses the value to be used as status code upon RPC completion.
This is an EXPERIMENTAL API.
- Returns
The StatusCode value for the RPC.
- details()[source]¶
Accesses the value to be used as detail string upon RPC completion.
This is an EXPERIMENTAL API.
- Returns
The details string of the RPC.
- abstract disable_next_message_compression()[source]¶
Disables compression for the next response message.
This is an EXPERIMENTAL method.
This method will override any compression configuration set during server creation or set on the call.
- Return type
None
- done()[source]¶
Return True if the RPC is done.
An RPC is done if the RPC is completed, cancelled or aborted.
This is an EXPERIMENTAL API.
- Returns
A bool indicates if the RPC is done.
- Return type
bool
- abstract invocation_metadata()[source]¶
Accesses the metadata sent by the client.
- Returns
The invocation metadata.
- Return type
Optional[grpc.aio._metadata.Metadata]
- abstract peer()[source]¶
Identifies the peer that invoked the RPC being serviced.
- Returns
A string identifying the peer that invoked the RPC being serviced. The string format is determined by gRPC runtime.
- Return type
str
- abstract peer_identities()[source]¶
Gets one or more peer identity(s).
Equivalent to servicer_context.auth_context().get(servicer_context.peer_identity_key())
- Returns
An iterable of the identities, or None if the call is not authenticated. Each identity is returned as a raw bytes type.
- Return type
Optional[Iterable[bytes]]
- abstract peer_identity_key()[source]¶
The auth property used to identify the peer.
For example, “x509_common_name” or “x509_subject_alternative_name” are used to identify an SSL peer.
- Returns
The auth property (string) that indicates the peer identity, or None if the call is not authenticated.
- Return type
Optional[str]
- abstract async read()[source]¶
Reads one message from the RPC.
Only one read operation is allowed simultaneously.
- Returns
A response message of the RPC.
- Raises
An RpcError exception if the read failed. –
- Return type
grpc.aio._typing.RequestType
- abstract async send_initial_metadata(initial_metadata)[source]¶
Sends the initial metadata value to the client.
This method need not be called by implementations if they have no metadata to add to what the gRPC runtime will transmit.
- Parameters
initial_metadata (Union[grpc.aio._metadata.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]) – The initial metadata.
- Return type
None
- abstract set_code(code)[source]¶
Sets the value to be used as status code upon RPC completion.
This method need not be called by method implementations if they wish the gRPC runtime to determine the status code of the RPC.
- Parameters
code (grpc.StatusCode) – A StatusCode object to be sent to the client.
- Return type
None
- abstract set_compression(compression)[source]¶
Set the compression algorithm to be used for the entire call.
This is an EXPERIMENTAL method.
- Parameters
compression (grpc.Compression) – An element of grpc.compression, e.g. grpc.compression.Gzip.
- Return type
None
- abstract set_details(details)[source]¶
Sets the value to be used the as detail string upon RPC completion.
This method need not be called by method implementations if they have no details to transmit.
- Parameters
details (str) – A UTF-8-encodable string to be sent to the client upon termination of the RPC.
- Return type
None
- abstract set_trailing_metadata(trailing_metadata)[source]¶
Sends the trailing metadata for the RPC.
This method need not be called by implementations if they have no metadata to add to what the gRPC runtime will transmit.
- Parameters
trailing_metadata (Union[grpc.aio._metadata.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]) – The trailing metadata.
- Return type
None
- time_remaining()[source]¶
Describes the length of allowed time remaining for the RPC.
- Returns
A nonnegative float indicating the length of allowed time in seconds remaining for the RPC to complete before it is considered to have timed out, or None if no deadline was specified for the RPC.
- Return type
float
Client-Side Interceptor¶
- class grpc.aio.ClientCallDetails(method, timeout, metadata, credentials, wait_for_ready)[source]¶
Describes an RPC to be invoked.
This is an EXPERIMENTAL API.
- Parameters
method (str) – The method name of the RPC.
timeout (Optional[float]) – An optional duration of time in seconds to allow for the RPC.
metadata (Optional[grpc.aio._metadata.Metadata]) – Optional metadata to be transmitted to the service-side of the RPC.
credentials (Optional[grpc.CallCredentials]) – An optional CallCredentials for the RPC.
wait_for_ready (Optional[bool]) – This is an EXPERIMENTAL argument. An optional flag to enable wait_for_ready mechanism.
- class grpc.aio.InterceptedUnaryUnaryCall(interceptors, request, timeout, metadata, credentials, wait_for_ready, channel, method, request_serializer, response_deserializer, loop)[source]¶
Used for running a UnaryUnaryCall wrapped by interceptors.
For the __await__ method is it is proxied to the intercepted call only when the interceptor task is finished.
- time_remaining()[source]¶
Describes the length of allowed time remaining for the RPC.
- Returns
A nonnegative float indicating the length of allowed time in seconds remaining for the RPC to complete before it is considered to have timed out, or None if no deadline was specified for the RPC.
- Return type
Optional[float]
- class grpc.aio.UnaryUnaryClientInterceptor[source]¶
Affords intercepting unary-unary invocations.
- abstract async intercept_unary_unary(continuation, client_call_details, request)[source]¶
Intercepts a unary-unary invocation asynchronously.
- Parameters
continuation (Callable[[grpc.aio._interceptor.ClientCallDetails, grpc.aio._typing.RequestType], grpc.aio._call.UnaryUnaryCall]) – A coroutine that proceeds with the invocation by executing the next interceptor in the chain or invoking the actual RPC on the underlying Channel. It is the interceptor’s responsibility to call it if it decides to move the RPC forward. The interceptor can use call = await continuation(client_call_details, request) to continue with the RPC. continuation returns the call to the RPC.
client_call_details (grpc.aio._interceptor.ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.
request (grpc.aio._typing.RequestType) – The request value for the RPC.
- Returns
An object with the RPC response.
- Raises
AioRpcError – Indicating that the RPC terminated with non-OK status.
asyncio.CancelledError – Indicating that the RPC was canceled.
- Return type
Union[grpc.aio._call.UnaryUnaryCall, grpc.aio._typing.ResponseType]
- class grpc.aio.UnaryStreamClientInterceptor[source]¶
Affords intercepting unary-stream invocations.
- abstract async intercept_unary_stream(continuation, client_call_details, request)[source]¶
Intercepts a unary-stream invocation asynchronously.
The function could return the call object or an asynchronous iterator, in case of being an asyncrhonous iterator this will become the source of the reads done by the caller.
- Parameters
continuation (Callable[[grpc.aio._interceptor.ClientCallDetails, grpc.aio._typing.RequestType], grpc.aio._call.UnaryStreamCall]) – A coroutine that proceeds with the invocation by executing the next interceptor in the chain or invoking the actual RPC on the underlying Channel. It is the interceptor’s responsibility to call it if it decides to move the RPC forward. The interceptor can use call = await continuation(client_call_details, request) to continue with the RPC. continuation returns the call to the RPC.
client_call_details (grpc.aio._interceptor.ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.
request (grpc.aio._typing.RequestType) – The request value for the RPC.
- Returns
The RPC Call or an asynchronous iterator.
- Raises
AioRpcError – Indicating that the RPC terminated with non-OK status.
asyncio.CancelledError – Indicating that the RPC was canceled.
- Return type
Union[AsyncIterable[Any], grpc.aio._call.UnaryStreamCall]
- class grpc.aio.StreamUnaryClientInterceptor[source]¶
Affords intercepting stream-unary invocations.
- abstract async intercept_stream_unary(continuation, client_call_details, request_iterator)[source]¶
Intercepts a stream-unary invocation asynchronously.
Within the interceptor the usage of the call methods like write or even awaiting the call should be done carefully, since the caller could be expecting an untouched call, for example for start writing messages to it.
- Parameters
continuation (Callable[[grpc.aio._interceptor.ClientCallDetails, grpc.aio._typing.RequestType], grpc.aio._call.StreamUnaryCall]) – A coroutine that proceeds with the invocation by executing the next interceptor in the chain or invoking the actual RPC on the underlying Channel. It is the interceptor’s responsibility to call it if it decides to move the RPC forward. The interceptor can use call = await continuation(client_call_details, request_iterator) to continue with the RPC. continuation returns the call to the RPC.
client_call_details (grpc.aio._interceptor.ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.
request_iterator (Union[Iterable[Any], AsyncIterable[Any]]) – The request iterator that will produce requests for the RPC.
- Returns
The RPC Call.
- Raises
AioRpcError – Indicating that the RPC terminated with non-OK status.
asyncio.CancelledError – Indicating that the RPC was canceled.
- Return type
grpc.aio._call.StreamUnaryCall
- class grpc.aio.StreamStreamClientInterceptor[source]¶
Affords intercepting stream-stream invocations.
- abstract async intercept_stream_stream(continuation, client_call_details, request_iterator)[source]¶
Intercepts a stream-stream invocation asynchronously.
Within the interceptor the usage of the call methods like write or even awaiting the call should be done carefully, since the caller could be expecting an untouched call, for example for start writing messages to it.
The function could return the call object or an asynchronous iterator, in case of being an asyncrhonous iterator this will become the source of the reads done by the caller.
- Parameters
continuation (Callable[[grpc.aio._interceptor.ClientCallDetails, grpc.aio._typing.RequestType], grpc.aio._call.StreamStreamCall]) – A coroutine that proceeds with the invocation by executing the next interceptor in the chain or invoking the actual RPC on the underlying Channel. It is the interceptor’s responsibility to call it if it decides to move the RPC forward. The interceptor can use call = await continuation(client_call_details, request_iterator) to continue with the RPC. continuation returns the call to the RPC.
client_call_details (grpc.aio._interceptor.ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.
request_iterator (Union[Iterable[Any], AsyncIterable[Any]]) – The request iterator that will produce requests for the RPC.
- Returns
The RPC Call or an asynchronous iterator.
- Raises
AioRpcError – Indicating that the RPC terminated with non-OK status.
asyncio.CancelledError – Indicating that the RPC was canceled.
- Return type
Union[AsyncIterable[Any], grpc.aio._call.StreamStreamCall]
Server-Side Interceptor¶
- class grpc.aio.ServerInterceptor[source]¶
Affords intercepting incoming RPCs on the service-side.
This is an EXPERIMENTAL API.
- abstract async intercept_service(continuation, handler_call_details)[source]¶
Intercepts incoming RPCs before handing them over to a handler.
- Parameters
continuation (Callable[[grpc.HandlerCallDetails], Awaitable[grpc.RpcMethodHandler]]) – A function that takes a HandlerCallDetails and proceeds to invoke the next interceptor in the chain, if any, or the RPC handler lookup logic, with the call details passed as an argument, and returns an RpcMethodHandler instance if the RPC is considered serviced, or None otherwise.
handler_call_details (grpc.HandlerCallDetails) – A HandlerCallDetails describing the RPC.
- Returns
An RpcMethodHandler with which the RPC may be serviced if the interceptor chooses to service this RPC, or None otherwise.
- Return type
Multi-Callable Interfaces¶
- class grpc.aio.UnaryUnaryMultiCallable[source]¶
Enables asynchronous invocation of a unary-call RPC.
- abstract __call__(request, *, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None)[source]¶
Asynchronously invokes the underlying RPC.
- Parameters
request (Any) – The request value for the RPC.
timeout (Optional[float]) – An optional duration of time in seconds to allow for the RPC.
metadata (Optional[Union[grpc.aio._metadata.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]]) – Optional metadata to be transmitted to the service-side of the RPC.
credentials (Optional[grpc.CallCredentials]) – An optional CallCredentials for the RPC. Only valid for secure Channel.
wait_for_ready (Optional[bool]) – This is an EXPERIMENTAL argument. An optional flag to enable wait_for_ready mechanism.
compression (Optional[grpc.Compression]) – An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option.
- Returns
A UnaryUnaryCall object.
- Raises
RpcError – Indicates that the RPC terminated with non-OK status. The raised RpcError will also be a Call for the RPC affording the RPC’s metadata, status code, and details.
- Return type
- class grpc.aio.UnaryStreamMultiCallable[source]¶
Enables asynchronous invocation of a server-streaming RPC.
- abstract __call__(request, *, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None)[source]¶
Asynchronously invokes the underlying RPC.
- Parameters
request (Any) – The request value for the RPC.
timeout (Optional[float]) – An optional duration of time in seconds to allow for the RPC.
metadata (Optional[Union[grpc.aio._metadata.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]]) – Optional metadata to be transmitted to the service-side of the RPC.
credentials (Optional[grpc.CallCredentials]) – An optional CallCredentials for the RPC. Only valid for secure Channel.
wait_for_ready (Optional[bool]) – This is an EXPERIMENTAL argument. An optional flag to enable wait_for_ready mechanism.
compression (Optional[grpc.Compression]) – An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option.
- Returns
A UnaryStreamCall object.
- Raises
RpcError – Indicates that the RPC terminated with non-OK status. The raised RpcError will also be a Call for the RPC affording the RPC’s metadata, status code, and details.
- Return type
- class grpc.aio.StreamUnaryMultiCallable[source]¶
Enables asynchronous invocation of a client-streaming RPC.
- abstract __call__(request_iterator=None, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None)[source]¶
Asynchronously invokes the underlying RPC.
- Parameters
request_iterator (Optional[Union[Iterable[Any], AsyncIterable[Any]]]) – An optional async iterable or iterable of request messages for the RPC.
timeout (Optional[float]) – An optional duration of time in seconds to allow for the RPC.
metadata (Optional[Union[grpc.aio._metadata.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]]) – Optional metadata to be transmitted to the service-side of the RPC.
credentials (Optional[grpc.CallCredentials]) – An optional CallCredentials for the RPC. Only valid for secure Channel.
wait_for_ready (Optional[bool]) – This is an EXPERIMENTAL argument. An optional flag to enable wait_for_ready mechanism.
compression (Optional[grpc.Compression]) – An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option.
- Returns
A StreamUnaryCall object.
- Raises
RpcError – Indicates that the RPC terminated with non-OK status. The raised RpcError will also be a Call for the RPC affording the RPC’s metadata, status code, and details.
- Return type
- class grpc.aio.StreamStreamMultiCallable[source]¶
Enables asynchronous invocation of a bidirectional-streaming RPC.
- abstract __call__(request_iterator=None, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None)[source]¶
Asynchronously invokes the underlying RPC.
- Parameters
request_iterator (Optional[Union[Iterable[Any], AsyncIterable[Any]]]) – An optional async iterable or iterable of request messages for the RPC.
timeout (Optional[float]) – An optional duration of time in seconds to allow for the RPC.
metadata (Optional[Union[grpc.aio._metadata.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]]) – Optional metadata to be transmitted to the service-side of the RPC.
credentials (Optional[grpc.CallCredentials]) – An optional CallCredentials for the RPC. Only valid for secure Channel.
wait_for_ready (Optional[bool]) – This is an EXPERIMENTAL argument. An optional flag to enable wait_for_ready mechanism.
compression (Optional[grpc.Compression]) – An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option.
- Returns
A StreamStreamCall object.
- Raises
RpcError – Indicates that the RPC terminated with non-OK status. The raised RpcError will also be a Call for the RPC affording the RPC’s metadata, status code, and details.
- Return type