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 (Sequence[Tuple[str, Any]] | None) – An optional list of key-value pairs (channel_arguments in gRPC Core runtime) to configure the channel.

  • compression (Compression | None) – An optional value indicating the compression method to be used over the lifetime of the channel.

  • interceptors (Sequence[ClientInterceptor] | None) – 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 (ChannelCredentials) – A ChannelCredentials instance.

  • options (Sequence[Tuple[str, Any]] | None) – An optional list of key-value pairs (channel_arguments in gRPC Core runtime) to configure the channel.

  • compression (Compression | None) – An optional value indicating the compression method to be used over the lifetime of the channel.

  • interceptors (Sequence[ClientInterceptor] | None) – 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 (float | None) –

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:

ChannelConnectivity

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 (Callable[[Any], bytes] | None) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.

  • response_deserializer (Callable[[bytes], Any] | None) – 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:

StreamStreamMultiCallable

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 (Callable[[Any], bytes] | None) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.

  • response_deserializer (Callable[[bytes], Any] | None) – 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:

StreamUnaryMultiCallable

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 (Callable[[Any], bytes] | None) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.

  • response_deserializer (Callable[[bytes], Any] | None) – 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:

UnaryStreamMultiCallable

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 (Callable[[Any], bytes] | None) – Optional serializer for serializing the request message. Request goes unserialized in case None is passed.

  • response_deserializer (Callable[[bytes], Any] | None) – 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:

UnaryUnaryMultiCallable

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 (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 (Executor | None) – A futures.ThreadPoolExecutor to be used by the Server to execute non-AsyncIO RPC handlers for migration purpose.

  • handlers (Sequence[GenericRpcHandler] | None) – 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 (Sequence[Any] | None) – 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 (Sequence[Tuple[str, Any]] | None) – An optional list of key-value pairs (channel_arguments in gRPC runtime) to configure the channel.

  • maximum_concurrent_rpcs (int | None) – The maximum number of concurrent RPCs this server will service before returning RESOURCE_EXHAUSTED status, or None to indicate no limit.

  • compression (Compression | None) – 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.

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[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 (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 (float | None) – 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:

  1. The server is stopped or terminated;

  2. 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 (float | None) – 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 (StatusCode) –

  • initial_metadata (Metadata) –

  • trailing_metadata (Metadata) –

  • details (str | None) –

  • debug_error_string (str | None) –

Return type:

None

code()[source]

Accesses the status code sent by the server.

Returns:

The grpc.StatusCode status code.

Return type:

StatusCode

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:

str | None

initial_metadata()[source]

Accesses the initial metadata sent by the server.

Returns:

The initial metadata received.

Return type:

Metadata

trailing_metadata()[source]

Accesses the trailing metadata sent by the server.

Returns:

The trailing metadata received.

Return type:

Metadata

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, str | bytes]) –

__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:

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

__setitem__(key, value)[source]

Calling metadata[<key>] = <value> Maps <value> to the first instance of <key>.

Parameters:
  • key (str) –

  • value (str | bytes) –

Return type:

None

delete_all(key)[source]

Delete all mappings for <key>.

Parameters:

key (str) –

Return type:

None

get_all(key)[source]

For compatibility with other Metadata abstraction objects (like in Java), this would return all items under the desired <key>.

Parameters:

key (str) –

Return type:

List[str | bytes]

RPC Context

class grpc.aio.RpcContext[source]

Provides RPC-related information and action.

abstract add_done_callback(callback)[source]

Registers a callback to be called on RPC termination.

Parameters:
  • callback (Callable[[Any], None]) – A callable object will be called with the call object as

  • argument. (its only) –

Return type:

None

abstract cancel()[source]

Cancels the RPC.

Idempotent and has no effect if the RPC has already terminated.

Returns:

A bool indicates if the cancellation is performed or not.

Return type:

bool

abstract cancelled()[source]

Return True if the RPC is cancelled.

The RPC is cancelled when the cancellation was requested with cancel().

Returns:

A bool indicates whether the RPC is cancelled or not.

Return type:

bool

abstract done()[source]

Return True if the RPC is done.

An RPC is done if the RPC is completed, cancelled or aborted.

Returns:

A bool indicates if the RPC is done.

Return type:

bool

abstract 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 | None

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:

StatusCode

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:

Metadata

abstract async trailing_metadata()[source]

Accesses the trailing metadata sent by the server.

Returns:

The trailing metadata.

Return type:

Metadata

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.

abstract __await__()[source]

Await the response message to be ready.

Returns:

The response message of the RPC.

Return type:

Generator[Any, None, ResponseType]

class grpc.aio.UnaryStreamCall(*args, **kwds)[source]
abstract __aiter__()[source]

Returns the async iterator representation that yields messages.

Under the hood, it is calling the “read” method.

Returns:

An async iterator object that yields messages.

Return type:

AsyncIterator[ResponseType]

abstract async read()[source]

Reads one message from the stream.

Read operations must be serialized when called from multiple coroutines.

Note that the iterator and read/write APIs may not be mixed on a single RPC.

Returns:

A response message, or an grpc.aio.EOF to indicate the end of the stream.

Return type:

_EOF | ResponseType

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:

Generator[Any, None, 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

abstract async write(request)[source]

Writes one message to the stream.

Note that the iterator and read/write APIs may not be mixed on a single RPC.

Raises:

An RpcError exception if the write failed.

Parameters:

request (RequestType) –

Return type:

None

class grpc.aio.StreamStreamCall(*args, **kwds)[source]
abstract __aiter__()[source]

Returns the async iterator representation that yields messages.

Under the hood, it is calling the “read” method.

Returns:

An async iterator object that yields messages.

Return type:

AsyncIterator[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

abstract async read()[source]

Reads one message from the stream.

Read operations must be serialized when called from multiple coroutines.

Note that the iterator and read/write APIs may not be mixed on a single RPC.

Returns:

A response message, or an grpc.aio.EOF to indicate the end of the stream.

Return type:

_EOF | ResponseType

abstract async write(request)[source]

Writes one message to the stream.

Note that the iterator and read/write APIs may not be mixed on a single RPC.

Raises:

An RpcError exception if the write failed.

Parameters:

request (RequestType) –

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 (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 (Metadata | Sequence[Tuple[str, 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:

NoReturn

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 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:

Metadata | None

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:

Iterable[bytes] | None

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:

str | None

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:

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 (Metadata | Sequence[Tuple[str, 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 (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.

Parameters:

compression (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 (Metadata | Sequence[Tuple[str, 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

trailing_metadata()[source]

Access value to be used as trailing metadata upon RPC completion.

This is an EXPERIMENTAL API.

Returns:

The trailing metadata for the RPC.

abstract async write(message)[source]

Writes one message to the RPC.

Only one write operation is allowed simultaneously.

Raises:

An RpcError exception if the write failed.

Parameters:

message (ResponseType) –

Return type:

None

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 (float | None) – An optional duration of time in seconds to allow for the RPC.

  • metadata (Metadata | None) – Optional metadata to be transmitted to the service-side of the RPC.

  • credentials (CallCredentials | None) – An optional CallCredentials for the RPC.

  • wait_for_ready (bool | None) – 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:

float | None

class grpc.aio.ClientInterceptor[source]

Base class used for all Aio Client Interceptor classes

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[[ClientCallDetails, RequestType], 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 (ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.

  • request (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:

UnaryUnaryCall | 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[[ClientCallDetails, RequestType], 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 (ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.

  • request (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:

AsyncIterable[Any] | 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[[ClientCallDetails, RequestType], 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 (ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.

  • request_iterator (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:

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[[ClientCallDetails, RequestType], 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 (ClientCallDetails) – A ClientCallDetails object describing the outgoing RPC.

  • request_iterator (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:

AsyncIterable[Any] | 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.

State can be passed from an interceptor to downstream interceptors via contextvars. The first interceptor is called from an empty contextvars.Context, and the same Context is used for downstream interceptors and for the final handler call. Note that there are no guarantees that interceptors and handlers will be called from the same thread.

Parameters:
  • continuation (Callable[[HandlerCallDetails], Awaitable[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 (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:

RpcMethodHandler

Multi-Callable Interfaces

class grpc.aio.UnaryUnaryMultiCallable(*args, **kwds)[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 (RequestType) – The request value for the RPC.

  • timeout (float | None) – An optional duration of time in seconds to allow for the RPC.

  • metadata (Metadata | Sequence[Tuple[str, str | bytes]] | None) – Optional metadata to be transmitted to the service-side of the RPC.

  • credentials (CallCredentials | None) – An optional CallCredentials for the RPC. Only valid for secure Channel.

  • wait_for_ready (bool | None) – An optional flag to enable wait_for_ready mechanism.

  • compression (Compression | None) – An element of grpc.compression, e.g. grpc.compression.Gzip.

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:

UnaryUnaryCall[RequestType, ResponseType]

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 (RequestType) – The request value for the RPC.

  • timeout (float | None) – An optional duration of time in seconds to allow for the RPC.

  • metadata (Metadata | Sequence[Tuple[str, str | bytes]] | None) – Optional metadata to be transmitted to the service-side of the RPC.

  • credentials (CallCredentials | None) – An optional CallCredentials for the RPC. Only valid for secure Channel.

  • wait_for_ready (bool | None) – An optional flag to enable wait_for_ready mechanism.

  • compression (Compression | None) – An element of grpc.compression, e.g. grpc.compression.Gzip.

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:

UnaryStreamCall[RequestType, ResponseType]

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 (Iterable[Any] | AsyncIterable[Any] | None) – An optional async iterable or iterable of request messages for the RPC.

  • timeout (float | None) – An optional duration of time in seconds to allow for the RPC.

  • metadata (Metadata | Sequence[Tuple[str, str | bytes]] | None) – Optional metadata to be transmitted to the service-side of the RPC.

  • credentials (CallCredentials | None) – An optional CallCredentials for the RPC. Only valid for secure Channel.

  • wait_for_ready (bool | None) – An optional flag to enable wait_for_ready mechanism.

  • compression (Compression | None) – An element of grpc.compression, e.g. grpc.compression.Gzip.

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:

StreamUnaryCall

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 (Iterable[Any] | AsyncIterable[Any] | None) – An optional async iterable or iterable of request messages for the RPC.

  • timeout (float | None) – An optional duration of time in seconds to allow for the RPC.

  • metadata (Metadata | Sequence[Tuple[str, str | bytes]] | None) – Optional metadata to be transmitted to the service-side of the RPC.

  • credentials (CallCredentials | None) – An optional CallCredentials for the RPC. Only valid for secure Channel.

  • wait_for_ready (bool | None) – An optional flag to enable wait_for_ready mechanism.

  • compression (Compression | None) – An element of grpc.compression, e.g. grpc.compression.Gzip.

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:

StreamStreamCall