gRPC

For documentation, examples, and more, see thePython gRPC page ongrpc.io.

Module Contents

Version

The version string is available asgrpc.__version__.

Create Client

grpc.insecure_channel(target,options=None,compression=None)[source]

Creates an insecure Channel to a server.

The returned Channel is thread-safe.

Parameters:
  • target – The server address

  • options – An optional list of key-value pairs (channel_argumentsin gRPC Core runtime) to configure the channel.

  • compression – An optional value indicating the compression method to beused over the lifetime of the channel.

Returns:

A Channel.

grpc.secure_channel(target,credentials,options=None,compression=None)[source]

Creates a secure Channel to a server.

The returned Channel is thread-safe.

Parameters:
  • target – The server address.

  • credentials – A ChannelCredentials instance.

  • options – An optional list of key-value pairs (channel_argumentsin gRPC Core runtime) to configure the channel.

  • compression – An optional value indicating the compression method to beused over the lifetime of the channel.

Returns:

A Channel.

grpc.intercept_channel(channel,*interceptors)[source]

Intercepts a channel through a set of interceptors.

Parameters:
  • channel – A Channel.

  • interceptors – Zero or more objects of typeUnaryUnaryClientInterceptor,UnaryStreamClientInterceptor,StreamUnaryClientInterceptor, orStreamStreamClientInterceptor.Interceptors are given control in the order they are listed.

Returns:

A Channel that intercepts each invocation via the provided interceptors.

Raises:

TypeError – If interceptor does not derive from any of UnaryUnaryClientInterceptor, UnaryStreamClientInterceptor, StreamUnaryClientInterceptor, or StreamStreamClientInterceptor.

Create Client Credentials

grpc.ssl_channel_credentials(root_certificates=None,private_key=None,certificate_chain=None)[source]

Creates a ChannelCredentials for use with an SSL-enabled Channel.

Parameters:
  • root_certificates – The PEM-encoded root certificates as a byte string,or None to retrieve them from a default location chosen by gRPCruntime.

  • private_key – The PEM-encoded private key as a byte string, or None if noprivate key should be used.

  • certificate_chain – The PEM-encoded certificate chain as a byte stringto use or None if no certificate chain should be used.

Returns:

A ChannelCredentials for use with an SSL-enabled Channel.

grpc.metadata_call_credentials(metadata_plugin,name=None)[source]

Construct CallCredentials from an AuthMetadataPlugin.

Parameters:
  • metadata_plugin – An AuthMetadataPlugin to use for authentication.

  • name – An optional name for the plugin.

Returns:

A CallCredentials.

grpc.access_token_call_credentials(access_token)[source]

Construct CallCredentials from an access token.

Parameters:

access_token – A string to place directly in the http requestauthorization header, for example“authorization: Bearer <access_token>”.

Returns:

A CallCredentials.

grpc.composite_call_credentials(*call_credentials)[source]

Compose multiple CallCredentials to make a new CallCredentials.

Parameters:

*call_credentials – At least two CallCredentials objects.

Returns:

A CallCredentials object composed of the given CallCredentials objects.

grpc.composite_channel_credentials(channel_credentials,*call_credentials)[source]

Compose a ChannelCredentials and one or more CallCredentials objects.

Parameters:
  • channel_credentials – A ChannelCredentials object.

  • *call_credentials – One or more CallCredentials objects.

Returns:

A ChannelCredentials composed of the given ChannelCredentials and

CallCredentials objects.

grpc.local_channel_credentials(local_connect_type=grpc.LocalConnectionType.LOCAL_TCP)[source]

Creates a local ChannelCredentials used for local connections.

This is an EXPERIMENTAL API.

Local credentials are used by local TCP endpoints (e.g. localhost:10000)also UDS connections.

The connections created by local channel credentials are notencrypted, but will be checked if they are local or not.The UDS connections are considered secure by providing peer authenticationand data confidentiality while TCP connections are considered insecure.

It is allowed to transmit call credentials over connections created bylocal channel credentials.

Local channel credentials are useful for 1) eliminating insecure_channel usage;2) enable unit testing for call credentials without setting up secrets.

Parameters:

local_connect_type – Local connection type (eithergrpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)

Returns:

A ChannelCredentials for use with a local Channel

grpc.compute_engine_channel_credentials(call_credentials)[source]

Creates a compute engine channel credential.

This credential can only be used in a GCP environment as it relies ona handshaker service. For more info about ALTS, seehttps://cloud.google.com/security/encryption-in-transit/application-layer-transport-security

This channel credential is expected to be used as part of a compositecredential in conjunction with a call credentials that authenticates theVM’s default service account. If used with any other sort of callcredential, the connection may suddenly and unexpectedly begin failing RPCs.

Create Server

grpc.server(thread_pool,handlers=None,interceptors=None,options=None,maximum_concurrent_rpcs=None,compression=None,xds=False)[source]

Creates a Server with which RPCs can be serviced.

Parameters:
  • thread_pool – A futures.ThreadPoolExecutor to be used by the Serverto execute RPC handlers.

  • handlers – 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 – 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 – An optional list of key-value pairs (channel_arguments in gRPC runtime)to configure the channel.

  • maximum_concurrent_rpcs – The maximum number of concurrent RPCs this serverwill service before returning RESOURCE_EXHAUSTED status, or None toindicate no limit.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip. This compression algorithm will be used for thelifetime of the server unless overridden.

  • xds – If set to true, retrieves server configuration via xDS. This is anEXPERIMENTAL option.

Returns:

A Server object.

Create Server Credentials

grpc.ssl_server_credentials(private_key_certificate_chain_pairs,root_certificates=None,require_client_auth=False)[source]

Creates a ServerCredentials for use with an SSL-enabled Server.

Parameters:
  • private_key_certificate_chain_pairs – A list of pairs of the form[PEM-encoded private key, PEM-encoded certificate chain].

  • root_certificates – An optional byte string of PEM-encoded client rootcertificates that the server will use to verify client authentication.If omitted, require_client_auth must also be False.

  • require_client_auth – A boolean indicating whether or not to requireclients to be authenticated. May only be True if root_certificatesis not None.

Returns:

A ServerCredentials for use with an SSL-enabled Server. Typically, thisobject is an argument to add_secure_port() method during server setup.

grpc.ssl_server_certificate_configuration(private_key_certificate_chain_pairs,root_certificates=None)[source]

Creates a ServerCertificateConfiguration for use with a Server.

Parameters:
  • private_key_certificate_chain_pairs – A collection of pairs ofthe form [PEM-encoded private key, PEM-encoded certificatechain].

  • root_certificates – An optional byte string of PEM-encoded client rootcertificates that the server will use to verify client authentication.

Returns:

A ServerCertificateConfiguration that can be returned in the certificate

configuration fetching callback.

grpc.dynamic_ssl_server_credentials(initial_certificate_configuration,certificate_configuration_fetcher,require_client_authentication=False)[source]

Creates a ServerCredentials for use with an SSL-enabled Server.

Parameters:
  • initial_certificate_configuration (ServerCertificateConfiguration) – Thecertificate configuration with which the server will be initialized.

  • certificate_configuration_fetcher (callable) – A callable that takes noarguments and should return a ServerCertificateConfiguration toreplace the server’s current certificate, or None for no change(i.e., the server will continue its current certificateconfig). The library will call this callback onevery newclient connection before starting the TLS handshake with theclient, thus allowing the user application to optionallyreturn a new ServerCertificateConfiguration that the server will thenuse for the handshake.

  • require_client_authentication – A boolean indicating whether or not torequire clients to be authenticated.

Returns:

A ServerCredentials.

grpc.local_server_credentials(local_connect_type=grpc.LocalConnectionType.LOCAL_TCP)[source]

Creates a local ServerCredentials used for local connections.

This is an EXPERIMENTAL API.

Local credentials are used by local TCP endpoints (e.g. localhost:10000)also UDS connections.

The connections created by local server credentials are notencrypted, but will be checked if they are local or not.The UDS connections are considered secure by providing peer authenticationand data confidentiality while TCP connections are considered insecure.

It is allowed to transmit call credentials over connections created by localserver credentials.

Local server credentials are useful for 1) eliminating insecure_channel usage;2) enable unit testing for call credentials without setting up secrets.

Parameters:

local_connect_type – Local connection type (eithergrpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)

Returns:

A ServerCredentials for use with a local Server

Local Connection Type

classgrpc.LocalConnectionType(value)[source]

Types of local connection for local credential creation.

UDS

Unix domain socket connections

LOCAL_TCP

Local TCP connections.

RPC Method Handlers

grpc.unary_unary_rpc_method_handler(behavior,request_deserializer=None,response_serializer=None)[source]

Creates an RpcMethodHandler for a unary-unary RPC method.

Parameters:
  • behavior – The implementation of an RPC that accepts one requestand returns one response.

  • request_deserializer – An optionaldeserializer for request deserialization.

  • response_serializer – An optionalserializer for response serialization.

Returns:

An RpcMethodHandler object that is typically used by grpc.Server.

grpc.unary_stream_rpc_method_handler(behavior,request_deserializer=None,response_serializer=None)[source]

Creates an RpcMethodHandler for a unary-stream RPC method.

Parameters:
  • behavior – The implementation of an RPC that accepts one requestand returns an iterator of response values.

  • request_deserializer – An optionaldeserializer for request deserialization.

  • response_serializer – An optionalserializer for response serialization.

Returns:

An RpcMethodHandler object that is typically used by grpc.Server.

grpc.stream_unary_rpc_method_handler(behavior,request_deserializer=None,response_serializer=None)[source]

Creates an RpcMethodHandler for a stream-unary RPC method.

Parameters:
  • behavior – The implementation of an RPC that accepts an iterator ofrequest values and returns a single response value.

  • request_deserializer – An optionaldeserializer for request deserialization.

  • response_serializer – An optionalserializer for response serialization.

Returns:

An RpcMethodHandler object that is typically used by grpc.Server.

grpc.stream_stream_rpc_method_handler(behavior,request_deserializer=None,response_serializer=None)[source]

Creates an RpcMethodHandler for a stream-stream RPC method.

Parameters:
  • behavior – The implementation of an RPC that accepts an iterator ofrequest values and returns an iterator of response values.

  • request_deserializer – An optionaldeserializer for request deserialization.

  • response_serializer – An optionalserializer for response serialization.

Returns:

An RpcMethodHandler object that is typically used by grpc.Server.

grpc.method_handlers_generic_handler(service,method_handlers)[source]

Creates a GenericRpcHandler from RpcMethodHandlers.

Parameters:
  • service – The name of the service that is implemented by themethod_handlers.

  • method_handlers – A dictionary that maps method names to correspondingRpcMethodHandler.

Returns:

A GenericRpcHandler. This is typically added to the grpc.Server objectwith add_generic_rpc_handlers() before starting the server.

Channel Ready Future

grpc.channel_ready_future(channel)[source]

Creates a Future that tracks when a Channel is ready.

Cancelling the Future does not affect the channel’s state machine.It merely decouples the Future from channel state machine.

Parameters:

channel – A Channel object.

Returns:

A Future object that matures when the channel connectivity isChannelConnectivity.READY.

Channel Connectivity

classgrpc.ChannelConnectivity(value)[source]

Mirrors grpc_connectivity_state in the gRPC Core.

IDLE

The channel is idle.

CONNECTING

The channel is connecting.

READY

The channel is ready to conduct RPCs.

TRANSIENT_FAILURE

The channel has seen a failure from which it expectsto recover.

SHUTDOWN

The channel has seen a failure from which it cannot recover.

gRPC Status Code

classgrpc.StatusCode(value)[source]

Mirrors grpc_status_code in the gRPC Core.

OK

Not an error; returned on success

CANCELLED

The operation was cancelled (typically by the caller).

UNKNOWN

Unknown error.

INVALID_ARGUMENT

Client specified an invalid argument.

DEADLINE_EXCEEDED

Deadline expired before operation could complete.

NOT_FOUND

Some requested entity (e.g., file or directory) was not found.

ALREADY_EXISTS

Some entity that we attempted to create (e.g., file or directory)already exists.

PERMISSION_DENIED

The caller does not have permission to execute the specifiedoperation.

UNAUTHENTICATED

The request does not have valid authentication credentials for theoperation.

RESOURCE_EXHAUSTED

Some resource has been exhausted, perhaps a per-user quota, orperhaps the entire file system is out of space.

FAILED_PRECONDITION

Operation was rejected because the system is not in a staterequired for the operation’s execution.

ABORTED

The operation was aborted, typically due to a concurrency issuelike sequencer check failures, transaction aborts, etc.

UNIMPLEMENTED

Operation is not implemented or not supported/enabled in this service.

INTERNAL

Internal errors. Means some invariants expected by underlyingsystem has been broken.

UNAVAILABLE

The service is currently unavailable.

DATA_LOSS

Unrecoverable data loss or corruption.

Channel Object

classgrpc.Channel[source]

Affords RPC invocation via generic methods on client-side.

Channel objects implement the Context Manager type, although they need notsupport being entered and exited multiple times.

__enter__()[source]

Enters the runtime context related to the channel object.

__exit__(exc_type,exc_val,exc_tb)[source]

Exits the runtime context related to the channel object.

abstractclose()[source]

Closes this Channel and releases all resources held by it.

Closing the Channel will immediately terminate all RPCs active with theChannel and it is not valid to invoke new RPCs with the Channel.

This method is idempotent.

abstractstream_stream(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]

Creates a StreamStreamMultiCallable for a stream-stream method.

Parameters:
  • method – The name of the RPC method.

  • request_serializer – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.

  • response_deserializer – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case Noneis passed.

  • _registered_method – Implementation Private. A bool representing whether the methodis registered.

Returns:

A StreamStreamMultiCallable value for the named stream-stream method.

abstractstream_unary(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]

Creates a StreamUnaryMultiCallable for a stream-unary method.

Parameters:
  • method – The name of the RPC method.

  • request_serializer – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.

  • response_deserializer – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case None ispassed.

  • _registered_method – Implementation Private. A bool representing whether the methodis registered.

Returns:

A StreamUnaryMultiCallable value for the named stream-unary method.

abstractsubscribe(callback,try_to_connect=False)[source]

Subscribe to this Channel’s connectivity state machine.

A Channel may be in any of the states described by ChannelConnectivity.This method allows application to monitor the state transitions.The typical use case is to debug or gain better visibility into gRPCruntime’s state.

Parameters:
  • callback – A callable to be invoked with ChannelConnectivity argument.ChannelConnectivity describes current state of the channel.The callable will be invoked immediately upon subscriptionand again for every change to ChannelConnectivity until itis unsubscribed or this Channel object goes out of scope.

  • try_to_connect – A boolean indicating whether or not this Channelshould attempt to connect immediately. If set to False, gRPCruntime decides when to connect.

abstractunary_stream(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]

Creates a UnaryStreamMultiCallable for a unary-stream method.

Parameters:
  • method – The name of the RPC method.

  • request_serializer – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.

  • response_deserializer – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case None ispassed.

  • _registered_method – Implementation Private. A bool representing whether the methodis registered.

Returns:

A UnaryStreamMultiCallable value for the name unary-stream method.

abstractunary_unary(method,request_serializer=None,response_deserializer=None,_registered_method=False)[source]

Creates a UnaryUnaryMultiCallable for a unary-unary method.

Parameters:
  • method – The name of the RPC method.

  • request_serializer – Optionalserializer for serializing the requestmessage. Request goes unserialized in case None is passed.

  • response_deserializer – Optionaldeserializer for deserializing theresponse message. Response goes undeserialized in case Noneis passed.

  • _registered_method – Implementation Private. A bool representing whether the methodis registered.

Returns:

A UnaryUnaryMultiCallable value for the named unary-unary method.

abstractunsubscribe(callback)[source]

Unsubscribes a subscribed callback from this Channel’s connectivity.

Parameters:
  • callback – A callable previously registered with this Channel from

  • method. (having been passed to its "subscribe")

Server Object

classgrpc.Server[source]

Services 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 – An iterable of GenericRpcHandlers that will be

  • RPCs. (used to service)

abstractadd_insecure_port(address)[source]

Opens an insecure port for accepting RPCs.

This method may only be called before starting the server.

Parameters:

address – The address for which to open a port. If the port is 0,or not specified in the address, then gRPC runtime will choose a port.

Returns:

An integer port on which server will accept RPC requests.

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.

If the same method have both generic and registered handler,registered handler will take precedence.

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.

This method may only be called before starting the server.

Parameters:
  • address – The address for which to open a port.if the port is 0, or not specified in the address, then gRPCruntime will choose a port.

  • server_credentials – A ServerCredentials object.

Returns:

An integer port on which server will accept RPC requests.

abstractstart()[source]

Starts this Server.

This method may only be called once. (i.e. it is not idempotent).

abstractstop(grace)[source]

Stops this Server.

This method immediately stop service of new RPCs in all 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 forgrace),all existing RPCs are aborted immediately and this methodblocks 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 havethe effect of stopping the Server sooner (passing None willhave the effect of stopping the server immediately). Passinga larger grace value in a subsequent callwill not have theeffect of stopping the server later (i.e. the most restrictivegrace value is used).

Parameters:

grace – A duration of time in seconds or None.

Returns:

A threading.Event that will be set when this Server has completelystopped, i.e. when running RPCs either complete or are aborted andall handlers have terminated.

wait_for_termination(timeout=None)[source]

Block current thread until 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:

  1. The server is stopped or terminated;

  2. 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 – A floating point number specifying a timeout for theoperation in seconds.

Returns:

A bool indicates if the operation times out.

Authentication & Authorization Objects

classgrpc.ChannelCredentials(credentials)[source]

An encapsulation of the data required to create a secure Channel.

This class has no supported interface - it exists to define the type of itsinstances and its instances exist to be passed to other functions. Forexample, ssl_channel_credentials returns an instance of this class andsecure_channel requires an instance of this class.

classgrpc.CallCredentials(credentials)[source]

An encapsulation of the data required to assert an identity over a call.

A CallCredentials has to be used with secure Channel, otherwise themetadata will not be transmitted to the server.

A CallCredentials may be composed with ChannelCredentials to always assertidentity for every call over that Channel.

This class has no supported interface - it exists to define the type of itsinstances and its instances exist to be passed to other functions.

classgrpc.AuthMetadataContext[source]

Provides information to call credentials metadata plugins.

service_url

A string URL of the service being called into.

method_name

A string of the fully qualified method name being called.

classgrpc.AuthMetadataPluginCallback[source]

Callback object received by a metadata plugin.

__call__(metadata,error)[source]

Passes to the gRPC runtime authentication metadata for an RPC.

Parameters:
  • metadata – Themetadata used to construct the CallCredentials.

  • error – An Exception to indicate error or None to indicate success.

classgrpc.AuthMetadataPlugin[source]

A specification for custom authentication.

__call__(context,callback)[source]

Implements authentication by passing metadata to a callback.

This method will be invoked asynchronously in a separate thread.

Parameters:
  • context – An AuthMetadataContext providing information on the RPC thatthe plugin is being called to authenticate.

  • callback – An AuthMetadataPluginCallback to be invoked eithersynchronously or asynchronously.

classgrpc.ServerCredentials(credentials)[source]

An encapsulation of the data required to open a secure port on a Server.

This class has no supported interface - it exists to define the type of itsinstances and its instances exist to be passed to other functions.

classgrpc.ServerCertificateConfiguration(certificate_configuration)[source]

A certificate configuration for use with an SSL-enabled Server.

Instances of this class can be returned in the certificate configurationfetching callback.

This class has no supported interface – it exists to define thetype of its instances and its instances exist to be passed toother functions.

gRPC Exceptions

exceptiongrpc.RpcError[source]

Raised by the gRPC library to indicate non-OK-status RPC termination.

RPC Context

classgrpc.RpcContext[source]

Provides RPC-related information and action.

abstractadd_callback(callback)[source]

Registers a callback to be called on RPC termination.

Parameters:

callback – A no-parameter callable to be called on RPC termination.

Returns:

True if the callback was added and will be called later; False if

the callback was not added and will not be called (because the RPCalready terminated or some other reason).

abstractcancel()[source]

Cancels the RPC.

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

abstractis_active()[source]

Describes whether the RPC is active or has terminated.

Returns:

True if RPC is active, False otherwise.

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.

Client-Side Context

classgrpc.Call[source]

Invocation-side utility object for an RPC.

abstractcode()[source]

Accesses the status code sent by the server.

This method blocks until the value is available.

Returns:

The StatusCode value for the RPC.

abstractdetails()[source]

Accesses the details sent by the server.

This method blocks until the value is available.

Returns:

The details string of the RPC.

abstractinitial_metadata()[source]

Accesses the initial metadata sent by the server.

This method blocks until the value is available.

Returns:

The initialmetadata.

abstracttrailing_metadata()[source]

Accesses the trailing metadata sent by the server.

This method blocks until the value is available.

Returns:

The trailingmetadata.

Client-Side Interceptor

classgrpc.ClientCallDetails[source]

Describes an RPC to be invoked.

method

The method name of the RPC.

timeout

An optional duration of time in seconds to allow for the RPC.

metadata

Optionalmetadata to be transmitted tothe service-side of the RPC.

credentials

An optional CallCredentials for the RPC.

wait_for_ready

An optional flag to enablewait_for_ready mechanism.

compression

An element of grpc.compression, e.g.grpc.compression.Gzip.

classgrpc.UnaryUnaryClientInterceptor[source]

Affords intercepting unary-unary invocations.

abstractintercept_unary_unary(continuation,client_call_details,request)[source]

Intercepts a unary-unary invocation asynchronously.

Parameters:
  • continuation – A function that proceeds with the invocation byexecuting the next interceptor in 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 useresponse_future = continuation(client_call_details, request)to continue with the RPC.continuation returns an object that isboth a Call for the RPC and a Future. In the event of RPCcompletion, the return Call-Future’s result value will bethe response message of the RPC. Should the event terminatewith non-OK status, the returned Call-Future’s exception valuewill be an RpcError.

  • client_call_details – A ClientCallDetails object describing theoutgoing RPC.

  • request – The request value for the RPC.

Returns:

An object that is both a Call for the RPC and a Future.In the event of RPC completion, the return Call-Future’sresult value will be the response message of the RPC.Should the event terminate with non-OK status, the returnedCall-Future’s exception value will be an RpcError.

classgrpc.UnaryStreamClientInterceptor[source]

Affords intercepting unary-stream invocations.

abstractintercept_unary_stream(continuation,client_call_details,request)[source]

Intercepts a unary-stream invocation.

Parameters:
  • continuation – A function that proceeds with the invocation byexecuting the next interceptor in 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 useresponse_iterator = continuation(client_call_details, request)to continue with the RPC.continuation returns an object that isboth a Call for the RPC and an iterator for response values.Drawing response values from the returned Call-iterator mayraise RpcError indicating termination of the RPC with non-OKstatus.

  • client_call_details – A ClientCallDetails object describing theoutgoing RPC.

  • request – The request value for the RPC.

Returns:

An object that is both a Call for the RPC and an iterator ofresponse values. Drawing response values from the returnedCall-iterator may raise RpcError indicating termination ofthe RPC with non-OK status. This objectshould also fulfill theFuture interface, though it may not.

classgrpc.StreamUnaryClientInterceptor[source]

Affords intercepting stream-unary invocations.

abstractintercept_stream_unary(continuation,client_call_details,request_iterator)[source]

Intercepts a stream-unary invocation asynchronously.

Parameters:
  • continuation – A function that proceeds with the invocation byexecuting the next interceptor in 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 useresponse_future = continuation(client_call_details, request_iterator)to continue with the RPC.continuation returns an object that isboth a Call for the RPC and a Future. In the event of RPC completion,the return Call-Future’s result value will be the response messageof the RPC. Should the event terminate with non-OK status, thereturned Call-Future’s exception value will be an RpcError.

  • client_call_details – A ClientCallDetails object describing theoutgoing RPC.

  • request_iterator – An iterator that yields request values for the RPC.

Returns:

An object that is both a Call for the RPC and a Future.In the event of RPC completion, the return Call-Future’sresult value will be the response message of the RPC.Should the event terminate with non-OK status, the returnedCall-Future’s exception value will be an RpcError.

classgrpc.StreamStreamClientInterceptor[source]

Affords intercepting stream-stream invocations.

abstractintercept_stream_stream(continuation,client_call_details,request_iterator)[source]

Intercepts a stream-stream invocation.

Parameters:
  • continuation – A function that proceeds with the invocation byexecuting the next interceptor in 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 useresponse_iterator = continuation(client_call_details, request_iterator)to continue with the RPC.continuation returns an object that isboth a Call for the RPC and an iterator for response values.Drawing response values from the returned Call-iterator mayraise RpcError indicating termination of the RPC with non-OKstatus.

  • client_call_details – A ClientCallDetails object describing theoutgoing RPC.

  • request_iterator – An iterator that yields request values for the RPC.

Returns:

An object that is both a Call for the RPC and an iterator ofresponse values. Drawing response values from the returnedCall-iterator may raise RpcError indicating termination ofthe RPC with non-OK status. This objectshould also fulfill theFuture interface, though it may not.

Service-Side Context

classgrpc.ServicerContext[source]

A context object passed to method implementations.

abstractabort(code,details)[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 – A StatusCode object to be sent to the client.It must not be StatusCode.OK.

  • details – A UTF-8-encodable string to be sent to the client upontermination of the RPC.

Raises:

Exception – An exception is always raised to signal the abortion the RPC to the gRPC runtime.

abstractabort_with_status(status)[source]

Raises an exception to terminate the RPC with a non-OK status.

The status passed as argument will supersede any existing status code,status message and trailing metadata.

This is an EXPERIMENTAL API.

Parameters:

status – A grpc.Status object. The status code in it must not beStatusCode.OK.

Raises:

Exception – An exception is always raised to signal the abortion the RPC to the gRPC runtime.

abstractauth_context()[source]

Gets the auth context for the call.

Returns:

A map of strings to an iterable of bytes for each auth property.

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.

disable_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.

abstractinvocation_metadata()[source]

Accesses the metadata sent by the client.

Returns:

The invocationmetadata.

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.

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.

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.

abstractsend_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.

Parameters:

initial_metadata – The initialmetadata.

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 – A StatusCode object to be sent to the client.

set_compression(compression)[source]

Set the compression algorithm to be used for the entire call.

Parameters:

compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

abstractset_details(details)[source]

Sets the value to be used as detail string upon RPC completion.

This method need not be called by method implementations if they haveno details to transmit.

Parameters:

details – A UTF-8-encodable string to be sent to the client upontermination of the RPC.

abstractset_trailing_metadata(trailing_metadata)[source]

Sets the trailing metadata for the RPC.

Sets the trailing metadata to be sent upon completion of the RPC.

If this method is invoked multiple times throughout the lifetime of anRPC, the value supplied in the final invocation will be the value sentover the wire.

This method need not be called by implementations if they have nometadata to add to what the gRPC runtime will transmit.

Parameters:

trailing_metadata – The trailingmetadata.

trailing_metadata()[source]

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

This is an EXPERIMENTAL API.

Returns:

The trailingmetadata for the RPC.

Service-Side Handler

classgrpc.RpcMethodHandler[source]

An implementation of a single RPC method.

request_streaming

Whether the RPC supports exactly one request messageor any arbitrary number of request messages.

response_streaming

Whether the RPC supports exactly one response messageor any arbitrary number of response messages.

request_deserializer

A callabledeserializer that accepts a byte string andreturns an object suitable to be passed to this object’s businesslogic, or None to indicate that this object’s business logic should bepassed the raw request bytes.

response_serializer

A callableserializer that accepts an object producedby this object’s business logic and returns a byte string, or None toindicate that the byte strings produced by this object’s business logicshould be transmitted on the wire as they are.

unary_unary

This object’s application-specific business logic as acallable value that takes a request value and a ServicerContext objectand returns a response value. Only non-None if both request_streamingand response_streaming are False.

unary_stream

This object’s application-specific business logic as acallable value that takes a request value and a ServicerContext objectand returns an iterator of response values. Only non-None ifrequest_streaming is False and response_streaming is True.

stream_unary

This object’s application-specific business logic as acallable value that takes an iterator of request values and aServicerContext object and returns a response value. Only non-None ifrequest_streaming is True and response_streaming is False.

stream_stream

This object’s application-specific business logic as acallable value that takes an iterator of request values and aServicerContext object and returns an iterator of response values.Only non-None if request_streaming and response_streaming are bothTrue.

classgrpc.HandlerCallDetails[source]

Describes an RPC that has just arrived for service.

method

The method name of the RPC.

invocation_metadata

Themetadata sent by the client.

classgrpc.GenericRpcHandler[source]

An implementation of arbitrarily many RPC methods.

abstractservice(handler_call_details)[source]

Returns the handler for servicing the RPC.

Parameters:

handler_call_details – A HandlerCallDetails describing the RPC.

Returns:

An RpcMethodHandler with which the RPC may be serviced if theimplementation chooses to service this RPC, or None otherwise.

classgrpc.ServiceRpcHandler[source]

An implementation of RPC methods belonging to a service.

A service handles RPC methods with structured names of the form‘/Service.Name/Service.Method’, where ‘Service.Name’ is the valuereturned by service_name(), and ‘Service.Method’ is the methodname. A service can have multiple method names, but only a singleservice name.

abstractservice_name()[source]

Returns this service’s name.

Returns:

The service name.

Service-Side Interceptor

classgrpc.ServerInterceptor[source]

Affords intercepting incoming RPCs on the service-side.

abstractintercept_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 – 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 – 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.

Multi-Callable Interfaces

classgrpc.UnaryUnaryMultiCallable[source]

Affords invoking a unary-unary RPC from client-side.

abstract__call__(request,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Synchronously invokes the underlying RPC.

Parameters:
  • request – The request value for the RPC.

  • timeout – An optional duration of time in seconds to allowfor the RPC.

  • metadata – Optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

The response value for the RPC.

Raises:

RpcError – Indicating 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.

abstractfuture(request,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Asynchronously invokes the underlying RPC.

Parameters:
  • request – The request value for the RPC.

  • timeout – An optional duration of time in seconds to allow forthe RPC.

  • metadata – Optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

An object that is both a Call for the RPC and a Future.In the event of RPC completion, the return Call-Future’s resultvalue will be the response message of the RPC.Should the event terminate with non-OK status,the returned Call-Future’s exception value will be an RpcError.

abstractwith_call(request,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Synchronously invokes the underlying RPC.

Parameters:
  • request – The request value for the RPC.

  • timeout – An optional durating of time in seconds to allow forthe RPC.

  • metadata – Optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

The response value for the RPC and a Call value for the RPC.

Raises:

RpcError – Indicating 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.

classgrpc.UnaryStreamMultiCallable[source]

Affords invoking a unary-stream RPC from client-side.

abstract__call__(request,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Invokes the underlying RPC.

Parameters:
  • request – The request value for the RPC.

  • timeout – An optional duration of time in seconds to allow forthe RPC. If None, the timeout is considered infinite.

  • metadata – An optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

An object that is a Call for the RPC, an iterator of responsevalues, and a Future for the RPC. Drawing response values from thereturned Call-iterator may raise RpcError indicating termination ofthe RPC with non-OK status.

classgrpc.StreamUnaryMultiCallable[source]

Affords invoking a stream-unary RPC from client-side.

abstract__call__(request_iterator,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Synchronously invokes the underlying RPC.

Parameters:
  • request_iterator – An iterator that yields request values forthe RPC.

  • timeout – An optional duration of time in seconds to allow forthe RPC. If None, the timeout is considered infinite.

  • metadata – Optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

The response value for the RPC.

Raises:

RpcError – Indicating that the RPC terminated with non-OK status. The raised RpcError will also implement grpc.Call, affording methods such as metadata, code, and details.

abstractfuture(request_iterator,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Asynchronously invokes the underlying RPC on the client.

Parameters:
  • request_iterator – An iterator that yields request values for the RPC.

  • timeout – An optional duration of time in seconds to allow forthe RPC. If None, the timeout is considered infinite.

  • metadata – Optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

An object that is both a Call for the RPC and a Future.In the event of RPC completion, the return Call-Future’s result valuewill be the response message of the RPC. Should the event terminatewith non-OK status, the returned Call-Future’s exception value willbe an RpcError.

abstractwith_call(request_iterator,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Synchronously invokes the underlying RPC on the client.

Parameters:
  • request_iterator – An iterator that yields request values forthe RPC.

  • timeout – An optional duration of time in seconds to allow forthe RPC. If None, the timeout is considered infinite.

  • metadata – Optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

The response value for the RPC and a Call object for the RPC.

Raises:

RpcError – Indicating 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.

classgrpc.StreamStreamMultiCallable[source]

Affords invoking a stream-stream RPC on client-side.

abstract__call__(request_iterator,timeout=None,metadata=None,credentials=None,wait_for_ready=None,compression=None)[source]

Invokes the underlying RPC on the client.

Parameters:
  • request_iterator – An iterator that yields request values for the RPC.

  • timeout – An optional duration of time in seconds to allow forthe RPC. If not specified, the timeout is considered infinite.

  • metadata – Optionalmetadata to be transmitted to theservice-side of the RPC.

  • credentials – An optional CallCredentials for the RPC. Only valid forsecure Channel.

  • wait_for_ready – An optional flag to enablewait_for_ready mechanism.

  • compression – An element of grpc.compression, e.g.grpc.compression.Gzip.

Returns:

An object that is a Call for the RPC, an iterator of responsevalues, and a Future for the RPC. Drawing response values from thereturned Call-iterator may raise RpcError indicating termination ofthe RPC with non-OK status.

Future Interfaces

exceptiongrpc.FutureTimeoutError[source]

Indicates that a method call on a Future timed out.

exceptiongrpc.FutureCancelledError[source]

Indicates that the computation underlying a Future was cancelled.

classgrpc.Future[source]

A representation of a computation in another control flow.

Computations represented by a Future may be yet to be begun,may be ongoing, or may have already completed.

abstractadd_done_callback(fn)[source]

Adds a function to be called at completion of the computation.

The callback will be passed this Future object describing the outcomeof the computation. Callbacks will be invoked after the future isterminated, whether successfully or not.

If the computation has already completed, the callback will be calledimmediately.

Exceptions raised in the callback will be logged at ERROR level, butwill not terminate any threads of execution.

Parameters:

fn – A callable taking this Future object as its single parameter.

abstractcancel()[source]

Attempts to cancel the computation.

This method does not block.

Returns:

Returns True if the computation was canceled.

Returns False under all other circumstances, for example:

  1. computation has begun and could not be canceled.

  2. computation has finished

  3. computation is scheduled for execution and it is impossible

    to determine its state without blocking.

Return type:

bool

abstractcancelled()[source]

Describes whether the computation was cancelled.

This method does not block.

Returns:

Returns True if the computation was cancelled before its result becameavailable.

Returns False under all other circumstances, for example:

  1. computation was not cancelled.

  2. computation’s result is available.

Return type:

bool

abstractdone()[source]

Describes whether the computation has taken place.

This method does not block.

Returns:

Returns True if the computation already executed or was cancelled.Returns False if the computation is scheduled for execution orcurrently executing.This is exactly opposite of the running() method’s result.

Return type:

bool

abstractexception(timeout=None)[source]

Return the exception raised by the computation.

This method may return immediately or may block.

Parameters:

timeout – The length of time in seconds to wait for the computation toterminate or be cancelled. If None, the call will block until thecomputations’s termination.

Returns:

The exception raised by the computation, or None if the computationdid not raise an exception.

Raises:
abstractresult(timeout=None)[source]

Returns the result of the computation or raises its exception.

This method may return immediately or may block.

Parameters:

timeout – The length of time in seconds to wait for the computation tofinish or be cancelled. If None, the call will block until thecomputations’s termination.

Returns:

The return value of the computation.

Raises:
  • FutureTimeoutError – If a timeout value is passed and the computation does not terminate within the allotted time.

  • FutureCancelledError – If the computation was cancelled.

  • Exception – If the computation raised an exception, this call will raise the same exception.

abstractrunning()[source]

Describes whether the computation is taking place.

This method does not block.

Returns:

Returns True if the computation is scheduled for execution orcurrently executing.

Returns False if the computation already executed or was cancelled.

abstracttraceback(timeout=None)[source]

Access the traceback of the exception raised by the computation.

This method may return immediately or may block.

Parameters:

timeout – The length of time in seconds to wait for the computationto terminate or be cancelled. If None, the call will block untilthe computation’s termination.

Returns:

The traceback of the exception raised by the computation, or Noneif the computation did not raise an exception.

Raises:

Compression

classgrpc.Compression(value)[source]

Indicates the compression method to be used for an RPC.

NoCompression

Do not use compression algorithm.

Deflate

Use “Deflate” compression algorithm.

Gzip

Use “Gzip” compression algorithm.

Runtime Protobuf Parsing

grpc.protos(protobuf_path)[source]

Returns a module generated by the indicated .proto file.

THIS IS AN EXPERIMENTAL API.

Use this function to retrieve classes corresponding to messagedefinitions in the .proto file.

To inspect the contents of the returned module, use the dir function.For example:

`protos=grpc.protos("foo.proto")print(dir(protos))`

The returned module object corresponds to the _pb2.py file generatedby protoc. The path is expected to be relative to an entry on sys.pathand all transitive dependencies of the file should also be resolvablefrom an entry on sys.path.

To completely disable the machinery behind this function, set theGRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to “true”.

Parameters:

protobuf_path – The path to the .proto file on the filesystem. This pathmust be resolvable from an entry on sys.path and so must all of itstransitive dependencies.

Returns:

A module object corresponding to the message code for the indicated.proto file. Equivalent to a generated _pb2.py file.

grpc.services(protobuf_path)[source]

Returns a module generated by the indicated .proto file.

THIS IS AN EXPERIMENTAL API.

Use this function to retrieve classes and functions corresponding toservice definitions in the .proto file, including both stub and servicerdefinitions.

To inspect the contents of the returned module, use the dir function.For example:

`services=grpc.services("foo.proto")print(dir(services))`

The returned module object corresponds to the _pb2_grpc.py file generatedby protoc. The path is expected to be relative to an entry on sys.pathand all transitive dependencies of the file should also be resolvablefrom an entry on sys.path.

To completely disable the machinery behind this function, set theGRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to “true”.

Parameters:

protobuf_path – The path to the .proto file on the filesystem. This pathmust be resolvable from an entry on sys.path and so must all of itstransitive dependencies.

Returns:

A module object corresponding to the stub/service code for the indicated.proto file. Equivalent to a generated _pb2_grpc.py file.

grpc.protos_and_services(protobuf_path)[source]

Returns a 2-tuple of modules corresponding to protos and services.

THIS IS AN EXPERIMENTAL API.

The return value of this function is equivalent to a call to protos and acall to services.

To completely disable the machinery behind this function, set theGRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to “true”.

Parameters:

protobuf_path – The path to the .proto file on the filesystem. This pathmust be resolvable from an entry on sys.path and so must all of itstransitive dependencies.

Returns:

A 2-tuple of module objects corresponding to (protos(path), services(path)).