gRPC AsyncIO API¶
Overview¶
gRPC AsyncIO API is thenew version of gRPC Python whose architecture istailored to AsyncIO. Underlying, it utilizes the same C-extension, gRPC C-Core,as existing stack, and it replaces all gRPC IO operations with methods providedby the AsyncIO library.
This API is stable. Feel free to open issues on our GitHub repogrpc/grpc for bugs or suggestions.
The design doc can be found here asgRFC.
Caveats¶
gRPC Async API objects may only be used on the thread on which they werecreated. 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 eventloop 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 logichappens, for example, managing one or more underlying connections, nameresolution, load balancing, flow control, etc.. If you are using ProtoBuf,Channel objects works best when further encapsulate into stub objects, then theapplication 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_argumentsin gRPC Core runtime) to configure the channel.
compression (Compression |None) – An optional value indicating the compression method to beused over the lifetime of the channel.
interceptors (Sequence[ClientInterceptor]|None) – An optional sequence of interceptors that will be executed forany 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_argumentsin gRPC Core runtime) to configure the channel.
compression (Compression |None) – An optional value indicating the compression method to beused over the lifetime of the channel.
interceptors (Sequence[ClientInterceptor]|None) – An optional sequence of interceptors that will be executed forany call executed with this channel.
- Returns:
An aio.Channel.
Channel Object¶
- classgrpc.aio.Channel[source]¶
Enables asynchronous RPC invocation as a client.
Channel objects implement the Asynchronous Context Manager (aka. asyncwith) type, although they are not supported to be entered and exitedmultiple times.
- abstractasync__aenter__()[source]¶
Starts an asynchronous context manager.
- Returns:
Channel the channel that was instantiated.
- abstractasync__aexit__(exc_type,exc_val,exc_tb)[source]¶
Finishes the asynchronous context manager by closing the channel.
Still active RPCs will be cancelled.
- abstractasyncchannel_ready()[source]¶
Creates a coroutine that blocks until the Channel is READY.
- Return type:
None
- abstractasyncclose(grace=None)[source]¶
Closes this Channel and releases all resources held by it.
This method immediately stops the channel from executing new RPCs inall cases.
If a grace period is specified, this method waits until all activeRPCs are finished or until the grace period is reached. RPCs that haven’tbeen terminated within the grace period are aborted.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)
- abstractget_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 guaranteedthat the return value of this function will eventually converge to thatstate.
- Parameters:
try_to_connect (bool) – a bool indicate whether the Channel should try toconnect to peer or not.
- Return type:
Returns: A ChannelConnectivity object.
- abstractstream_stream(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]¶
Creates a StreamStreamMultiCallable for a stream-stream method.
- Parameters:
method (str) – The name of the RPC method.
request_serializer (Callable[[Any],bytes]|None) – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.
response_deserializer (Callable[[bytes],Any]|None) – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case Noneis passed.
_registered_method (bool |None) – Implementation Private. Optional: A bool representingwhether the method is registered.
- Returns:
A StreamStreamMultiCallable value for the named stream-stream method.
- Return type:
- abstractstream_unary(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]¶
Creates a StreamUnaryMultiCallable for a stream-unary method.
- Parameters:
method (str) – The name of the RPC method.
request_serializer (Callable[[Any],bytes]|None) – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.
response_deserializer (Callable[[bytes],Any]|None) – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case Noneis passed.
_registered_method (bool |None) – Implementation Private. Optional: A bool representingwhether the method is registered.
- Returns:
A StreamUnaryMultiCallable value for the named stream-unary method.
- Return type:
- abstractunary_stream(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]¶
Creates a UnaryStreamMultiCallable for a unary-stream method.
- Parameters:
method (str) – The name of the RPC method.
request_serializer (Callable[[Any],bytes]|None) – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.
response_deserializer (Callable[[bytes],Any]|None) – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case Noneis passed.
_registered_method (bool |None) – Implementation Private. Optional: A bool representingwhether the method is registered.
- Returns:
A UnaryStreamMultiCallable value for the named unary-stream method.
- Return type:
- abstractunary_unary(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]¶
Creates a UnaryUnaryMultiCallable for a unary-unary method.
- Parameters:
method (str) – The name of the RPC method.
request_serializer (Callable[[Any],bytes]|None) – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.
response_deserializer (Callable[[bytes],Any]|None) – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case Noneis passed.
_registered_method (bool |None) – Implementation Private. Optional: A bool representingwhether the method is registered.
- Returns:
A UnaryUnaryMultiCallable value for the named unary-unary method.
- Return type:
- abstractasyncwait_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 connectivitystate from the “last_observed_state”. If the state is alreadydifferent, 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 canchange arbitrary many times during the race, so there is no way toobserve 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 representingthe 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 theServer 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 timebefore the server is started.
interceptors (Sequence[Any]|None) – An optional list of ServerInterceptor objects that observeand optionally manipulate the incoming RPCs before handing them over tohandlers. The interceptors are given control in the order they arespecified. 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 serverwill service before returning RESOURCE_EXHAUSTED status, or None toindicate no limit.
compression (Compression |None) – An element of grpc.compression, e.g.grpc.compression.Gzip. This compression algorithm will be used for thelifetime of the server unless overridden by set_compression.
- Returns:
A Server object.
Server Object¶
- classgrpc.aio.Server[source]¶
Serves RPCs.
- abstractadd_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
- abstractadd_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
- add_registered_method_handlers(service_name,method_handlers)[source]¶
Registers GenericRpcHandlers with this Server.
This method is only safe to call before the server is started.
- Parameters:
service_name – The service name.
method_handlers – A dictionary that maps method names to correspondingRpcMethodHandler.
- abstractadd_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 gRPCruntime 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
- abstractasyncstart()[source]¶
Starts this Server.
This method may only be called once. (i.e. it is not idempotent).
- Return type:
None
- abstractasyncstop(grace)[source]¶
Stops this Server.
This method immediately stops the server from servicing new RPCs inall cases.
If a grace period is specified, this method waits until all activeRPCs are finished or until the grace period is reached. RPCs that haven’tbeen terminated within the grace period are aborted.If a grace period is not specified (by passing None for grace), allexisting RPCs are aborted immediately and this method blocks untilthe last RPC handler terminates.
This method is idempotent and may be called at any time. Passing asmaller grace value in a subsequent call will have the effect ofstopping the Server sooner (passing None will have the effect ofstopping the server immediately). Passing a larger grace value in asubsequent 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
- abstractasyncwait_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, andit will block until one of the two following conditions are met:
The server is stopped or terminated;
A timeout occurs if timeout is notNone.
The timeout argument works in the same way asthreading.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 theoperation in seconds.
- Returns:
A bool indicates if the operation times out.
- Return type:
bool
gRPC Exceptions¶
- exceptiongrpc.aio.BaseError¶
The base class for exceptions generated by gRPC AsyncIO stack.
- exceptiongrpc.aio.UsageError¶
Raised when the usage of API by applications is inappropriate.
For example, trying to invoke RPC on a closed channel, mixing two stylesof streaming API on the client side. This exception should not besuppressed.
- exceptiongrpc.aio.AbortError¶
Raised when calling abort in servicer methods.
This exception should not be suppressed. Applications may catch it toperform certain clean-up logic, and then re-raise it.
- exceptiongrpc.aio.InternalError¶
Raised upon unexpected errors in native code.
- exceptiongrpc.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 aredetermined. 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:
Thegrpc.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:
str | None
gRPC Metadata¶
- classgrpc.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]¶
delmetadata[<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 thosemapped 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
RPC Context¶
- classgrpc.aio.RpcContext[source]¶
Provides RPC-related information and action.
- abstractadd_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
- abstractcancel()[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
- abstractcancelled()[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
- abstractdone()[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
- abstracttime_remaining()[source]¶
Describes the length of allowed time remaining for the RPC.
- Returns:
A nonnegative float indicating the length of allowed time in secondsremaining for the RPC to complete before it is considered to havetimed out, or None if no deadline was specified for the RPC.
- Return type:
float | None
Client-Side Context¶
- classgrpc.aio.Call[source]¶
The abstract base class of an RPC on the client-side.
- abstractasynccode()[source]¶
Accesses the status code sent by the server.
- Returns:
The StatusCode value for the RPC.
- Return type:
- abstractasyncdetails()[source]¶
Accesses the details sent by the server.
- Returns:
The details string of the RPC.
- Return type:
str
- abstractasyncwait_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 connectionfailure.
This method is recommended for building retry mechanisms.
- Return type:
None
- classgrpc.aio.UnaryUnaryCall[source]¶
The abstract base class of a unary-unary RPC on the client-side.
- classgrpc.aio.UnaryStreamCall[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]
- abstractasyncread()[source]¶
Reads one message from the stream.
Read operations must be serialized when called from multiplecoroutines.
Note that the iterator and read/write APIs may not be mixed ona single RPC.
- Returns:
A response message, or angrpc.aio.EOF to indicate the end of thestream.
- Return type:
_EOF |ResponseType
- classgrpc.aio.StreamUnaryCall[source]¶
- abstract__await__()[source]¶
Await the response message to be ready.
- Returns:
The response message of the stream.
- Return type:
Generator[Any, None,ResponseType]
- classgrpc.aio.StreamStreamCall[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]
- abstractasyncdone_writing()[source]¶
Notifies server that the client is done sending messages.
After done_writing is called, any additional invocation to the writefunction will fail. This function is idempotent.
- Return type:
None
- abstractasyncread()[source]¶
Reads one message from the stream.
Read operations must be serialized when called from multiplecoroutines.
Note that the iterator and read/write APIs may not be mixed ona single RPC.
- Returns:
A response message, or angrpc.aio.EOF to indicate the end of thestream.
- Return type:
_EOF |ResponseType
Server-Side Context¶
- classgrpc.aio.ServicerContext[source]¶
A context object passed to method implementations.
- abstractasyncabort(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 supersede any existingones.
- 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 upontermination of the RPC.
trailing_metadata (Metadata |Sequence[Tuple[str,str |bytes]]) – A sequence of tuple represents the trailingmetadata.
- 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 contextobject as its only argument.
- Return type:
None
- abstractauth_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.
- abstractdisable_next_message_compression()[source]¶
Disables compression for the next response message.
This method will override any compression configuration set duringserver 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
- abstractpeer()[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
- abstractpeer_identities()[source]¶
Gets one or more peer identity(s).
Equivalent toservicer_context.auth_context().get(servicer_context.peer_identity_key())
- Returns:
An iterable of the identities, or None if the call is notauthenticated. Each identity is returned as a raw bytes type.
- Return type:
Iterable[bytes] | None
- abstractpeer_identity_key()[source]¶
The auth property used to identify the peer.
For example, “x509_common_name” or “x509_subject_alternative_name” areused to identify an SSL peer.
- Returns:
The auth property (string) that indicates thepeer identity, or None if the call is not authenticated.
- Return type:
str | None
- abstractasyncread()[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
- abstractasyncsend_initial_metadata(initial_metadata)[source]¶
Sends the initial metadata value to the client.
This method need not be called by implementations if they have nometadata to add to what the gRPC runtime will transmit.
- abstractset_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 wishthe 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
- abstractset_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
- abstractset_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 haveno details to transmit.
- Parameters:
details (str) – A UTF-8-encodable string to be sent to the client upontermination of the RPC.
- Return type:
None
- abstractset_trailing_metadata(trailing_metadata)[source]¶
Sends the trailing metadata for the RPC.
This method need not be called by implementations if they have nometadata to add to what the gRPC runtime will transmit.
- time_remaining()[source]¶
Describes the length of allowed time remaining for the RPC.
- Returns:
A nonnegative float indicating the length of allowed time in secondsremaining for the RPC to complete before it is considered to havetimed out, or None if no deadline was specified for the RPC.
- Return type:
float
Client-Side Interceptor¶
- classgrpc.aio.ClientCallDetails(method,timeout,metadata,credentials,wait_for_ready)[source]¶
Describes an RPC to be invoked.
This is an EXPERIMENTAL API.
- Parameters:
method (bytes) – 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 ofthe RPC.
credentials (CallCredentials |None) – An optional CallCredentials for the RPC.
wait_for_ready (bool |None) – An optional flag to enablewait_for_ready mechanism.
- classgrpc.aio.InterceptedUnaryUnaryCall(interceptors,request,timeout,metadata,credentials,wait_for_ready,channel,method,request_serializer,response_deserializer,loop)[source]¶
Used for running aUnaryUnaryCall wrapped by interceptors.
For the__await__ method is it is proxied to the intercepted call only whenthe interceptor task is finished.
- Parameters:
interceptors (Sequence[UnaryUnaryClientInterceptor])
request (RequestType)
timeout (Optional[float])
metadata (Metadata)
credentials (Optional[grpc.CallCredentials])
wait_for_ready (Optional[bool])
channel (cygrpc.AioChannel)
method (bytes)
request_serializer (Optional[SerializingFunction])
response_deserializer (Optional[DeserializingFunction])
loop (asyncio.AbstractEventLoop)
- time_remaining()[source]¶
Describes the length of allowed time remaining for the RPC.
- Returns:
A nonnegative float indicating the length of allowed time in secondsremaining for the RPC to complete before it is considered to havetimed out, or None if no deadline was specified for the RPC.
- Return type:
float | None
- classgrpc.aio.UnaryUnaryClientInterceptor[source]¶
Affords intercepting unary-unary invocations.
- abstractasyncintercept_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 byexecuting the next interceptor in the chain or invoking theactual RPC on the underlying Channel. It is the interceptor’sresponsibility to call it if it decides to move the RPC forward.The interceptor can usecall = await continuation(client_call_details, request)to continue with the RPC.continuation returns the call to theRPC.
client_call_details (ClientCallDetails) – A ClientCallDetails object describing theoutgoing 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
- classgrpc.aio.UnaryStreamClientInterceptor[source]¶
Affords intercepting unary-stream invocations.
- abstractasyncintercept_unary_stream(continuation,client_call_details,request)[source]¶
Intercepts a unary-stream invocation asynchronously.
The function could return the call object or an asynchronousiterator, in case of being an asyncrhonous iterator this willbecome the source of the reads done by the caller.
- Parameters:
continuation (Callable[[ClientCallDetails,RequestType],UnaryStreamCall]) – A coroutine that proceeds with the invocation byexecuting the next interceptor in the chain or invoking theactual RPC on the underlying Channel. It is the interceptor’sresponsibility to call it if it decides to move the RPC forward.The interceptor can usecall = await continuation(client_call_details, request)to continue with the RPC.continuation returns the call to theRPC.
client_call_details (ClientCallDetails) – A ClientCallDetails object describing theoutgoing 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
- classgrpc.aio.StreamUnaryClientInterceptor[source]¶
Affords intercepting stream-unary invocations.
- abstractasyncintercept_stream_unary(continuation,client_call_details,request_iterator)[source]¶
Intercepts a stream-unary invocation asynchronously.
Within the interceptor the usage of the call methods likewrite oreven awaiting the call should be done carefully, since the callercould be expecting an untouched call, for example for start writingmessages to it.
- Parameters:
continuation (Callable[[ClientCallDetails,RequestType],StreamUnaryCall]) – A coroutine that proceeds with the invocation byexecuting the next interceptor in the chain or invoking theactual RPC on the underlying Channel. It is the interceptor’sresponsibility to call it if it decides to move the RPC forward.The interceptor can usecall = await continuation(client_call_details, request_iterator)to continue with the RPC.continuation returns the call to theRPC.
client_call_details (ClientCallDetails) – A ClientCallDetails object describing theoutgoing RPC.
request_iterator (Iterable[Any]|AsyncIterable[Any]) – The request iterator that will produce requestsfor 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
- classgrpc.aio.StreamStreamClientInterceptor[source]¶
Affords intercepting stream-stream invocations.
- abstractasyncintercept_stream_stream(continuation,client_call_details,request_iterator)[source]¶
Intercepts a stream-stream invocation asynchronously.
Within the interceptor the usage of the call methods likewrite oreven awaiting the call should be done carefully, since the callercould be expecting an untouched call, for example for start writingmessages to it.
The function could return the call object or an asynchronousiterator, in case of being an asyncrhonous iterator this willbecome the source of the reads done by the caller.
- Parameters:
continuation (Callable[[ClientCallDetails,RequestType],StreamStreamCall]) – A coroutine that proceeds with the invocation byexecuting the next interceptor in the chain or invoking theactual RPC on the underlying Channel. It is the interceptor’sresponsibility to call it if it decides to move the RPC forward.The interceptor can usecall = await continuation(client_call_details, request_iterator)to continue with the RPC.continuation returns the call to theRPC.
client_call_details (ClientCallDetails) – A ClientCallDetails object describing theoutgoing RPC.
request_iterator (Iterable[Any]|AsyncIterable[Any]) – The request iterator that will produce requestsfor 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¶
- classgrpc.aio.ServerInterceptor[source]¶
Affords intercepting incoming RPCs on the service-side.
This is an EXPERIMENTAL API.
- abstractasyncintercept_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 interceptorsvia contextvars. The first interceptor is called from an emptycontextvars.Context, and the same Context is used for downstreaminterceptors and for the final handler call. Note that there are noguarantees that interceptors and handlers will be called from thesame thread.
- Parameters:
continuation (Callable[[HandlerCallDetails],Awaitable[RpcMethodHandler]]) – A function that takes a HandlerCallDetails andproceeds to invoke the next interceptor in the chain, if any,or the RPC handler lookup logic, with the call details passedas an argument, and returns an RpcMethodHandler instance ifthe 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 theinterceptor chooses to service this RPC, or None otherwise.
- Return type:
Multi-Callable Interfaces¶
- classgrpc.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 (RequestType) – The request value for the RPC.
timeout (float |None) – An optional duration of time in seconds to allowfor the RPC.
metadata (Metadata |Sequence[Tuple[str,str |bytes]]|None) – Optionalmetadata to be transmitted to theservice-side of the RPC.
credentials (CallCredentials |None) – An optional CallCredentials for the RPC. Only valid forsecure Channel.
wait_for_ready (bool |None) – An optional flag to enablewait_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]
- classgrpc.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 allowfor the RPC.
metadata (Metadata |Sequence[Tuple[str,str |bytes]]|None) – Optionalmetadata to be transmitted to theservice-side of the RPC.
credentials (CallCredentials |None) – An optional CallCredentials for the RPC. Only valid forsecure Channel.
wait_for_ready (bool |None) – An optional flag to enablewait_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]
- classgrpc.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 requestmessages for the RPC.
timeout (float |None) – An optional duration of time in seconds to allowfor the RPC.
metadata (Metadata |Sequence[Tuple[str,str |bytes]]|None) – Optionalmetadata to be transmitted to theservice-side of the RPC.
credentials (CallCredentials |None) – An optional CallCredentials for the RPC. Only valid forsecure Channel.
wait_for_ready (bool |None) – An optional flag to enablewait_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:
- classgrpc.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 requestmessages for the RPC.
timeout (float |None) – An optional duration of time in seconds to allowfor the RPC.
metadata (Metadata |Sequence[Tuple[str,str |bytes]]|None) – Optionalmetadata to be transmitted to theservice-side of the RPC.
credentials (CallCredentials |None) – An optional CallCredentials for the RPC. Only valid forsecure Channel.
wait_for_ready (bool |None) – An optional flag to enablewait_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: