Subscriber Client API#
-
class
google.cloud.pubsub_v1.subscriber.client.
Client
(**kwargs)[source]# A subscriber client for Google Cloud Pub/Sub.
This creates an object that is capable of subscribing to messages. Generally, you can instantiate this client with no arguments, and you get sensible defaults.
- Parameters
kwargs (dict) – Any additional arguments provided are sent as keyword keyword arguments to the underlying
SubscriberClient
. Generally you should not need to set additional keyword arguments. Optionally, regional endpoints can be set viaclient_options
that takes a single key-value pair that defines the endpoint.
Example:
from google.cloud import pubsub_v1 subscriber_client = pubsub_v1.SubscriberClient( # Optional client_options = { "api_endpoint": REGIONAL_ENDPOINT } )
-
acknowledge
(subscription, ack_ids, retry=<object object>, timeout=<object object>, metadata=None)# Acknowledges the messages associated with the
ack_ids
in theAcknowledgeRequest
. The Pub/Sub system can remove the relevant messages from the subscription.Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> # TODO: Initialize `ack_ids`: >>> ack_ids = [] >>> >>> client.acknowledge(subscription, ack_ids)
- Parameters
subscription (str) – The subscription whose message is being acknowledged. Format is
projects/{project}/subscriptions/{sub}
.ack_ids (list[str]) – The acknowledgment ID for the messages being acknowledged that was returned by the Pub/Sub system in the
Pull
response. Must not be empty.retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
property
api
# The underlying gapic API client.
-
create_snapshot
(name, subscription, labels=None, retry=<object object>, timeout=<object object>, metadata=None)# Creates a snapshot from the requested subscription. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. If the snapshot already exists, returns
ALREADY_EXISTS
. If the requested subscription doesn’t exist, returnsNOT_FOUND
. If the backlog in the subscription is too old – and the resulting snapshot would expire in less than 1 hour – thenFAILED_PRECONDITION
is returned. See also theSnapshot.expire_time
field. If the name is not provided in the request, the server will assign a random name for this snapshot on the same project as the subscription, conforming to the resource name format. The generated name is populated in the returned Snapshot object. Note that for REST API requests, you must specify a name in the request.Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> name = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.create_snapshot(name, subscription)
- Parameters
name (str) – Optional user-provided name for this snapshot. If the name is not provided in the request, the server will assign a random name for this snapshot on the same project as the subscription. Note that for REST API requests, you must specify a name. See the resource name rules. Format is
projects/{project}/snapshots/{snap}
.subscription (str) – The subscription whose backlog the snapshot retains. Specifically, the created snapshot is guaranteed to retain: (a) The existing backlog on the subscription. More precisely, this is defined as the messages in the subscription’s backlog that are unacknowledged upon the successful completion of the
CreateSnapshot
request; as well as: (b) Any messages published to the subscription’s topic following the successful completion of the CreateSnapshot request. Format isprojects/{project}/subscriptions/{sub}
.labels (dict[str -> str]) – See <a href=”https://cloud.google.com/pubsub/docs/labels”> Creating and managing labels</a>.
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
Snapshot
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
create_subscription
(name, topic, push_config=None, ack_deadline_seconds=None, retain_acked_messages=None, message_retention_duration=None, labels=None, enable_message_ordering=None, expiration_policy=None, dead_letter_policy=None, retry=<object object>, timeout=<object object>, metadata=None)# Creates a subscription to a given topic. See the resource name rules. If the subscription already exists, returns
ALREADY_EXISTS
. If the corresponding topic doesn’t exist, returnsNOT_FOUND
.If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic, conforming to the resource name format. The generated name is populated in the returned Subscription object. Note that for REST API requests, you must specify a name in the request.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.create_subscription(name, topic)
- Parameters
name (str) – The name of the subscription. It must have the format “projects/{project}/subscriptions/{subscription}”. {subscription} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9]), dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with “goog”
topic (str) – The name of the topic from which this subscription is receiving messages. Format is
projects/{project}/topics/{topic}
. The value of this field will be_deleted-topic_
if the topic has been deleted.push_config (Union[dict, PushConfig]) –
If push delivery is used with this subscription, this field is used to configure it. An empty
pushConfig
signifies that the subscriber will pull and ack messages using API methods.If a dict is provided, it must be of the same form as the protobuf message
PushConfig
ack_deadline_seconds (int) –
The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to acknowledge receipt before resending the message. In the interval after the message is delivered and before it is acknowledged, it is considered to be outstanding. During that time period, the message will not be redelivered (on a best-effort basis).
For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call
ModifyAckDeadline
with the correspondingack_id
if using non-streaming pull or send theack_id
in aStreamingModifyAckDeadlineRequest
if using streaming pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used.For push delivery, this value is also used to set the request timeout for the call to the push endpoint.
If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message.
retain_acked_messages (bool) – Indicates whether to retain acknowledged messages. If true, then messages are not expunged from the subscription’s backlog, even if they are acknowledged, until they fall out of the
message_retention_duration
window. This must be true if you would like to Seek to a timestamp.message_retention_duration (Union[dict, Duration]) –
How long to retain unacknowledged messages in the subscription’s backlog, from the moment a message is published. If
retain_acked_messages
is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time aSeek
can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes.If a dict is provided, it must be of the same form as the protobuf message
Duration
labels (dict[str -> str]) – See <a href=”https://cloud.google.com/pubsub/docs/labels”> Creating and managing labels</a>.
enable_message_ordering (bool) – If true, messages published with the same
ordering_key
inPubsubMessage
will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order. EXPERIMENTAL: This feature is part of a closed alpha release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy.expiration_policy (Union[dict, ExpirationPolicy]) –
A policy that specifies the conditions for this subscription’s expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If
expiration_policy
is not set, a default policy withttl
of 31 days will be used. The minimum allowed value forexpiration_policy.ttl
is 1 day.If a dict is provided, it must be of the same form as the protobuf message
ExpirationPolicy
dead_letter_policy (Union[dict, DeadLetterPolicy]) –
A policy that specifies the conditions for dead lettering messages in this subscription. If dead_letter_policy is not set, dead lettering is disabled.
The Cloud Pub/Sub service account associated with this subscriptions’s parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to Acknowledge() messages on this subscription. EXPERIMENTAL: This feature is part of a closed alpha release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy.
If a dict is provided, it must be of the same form as the protobuf message
DeadLetterPolicy
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
Subscription
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
delete_snapshot
(snapshot, retry=<object object>, timeout=<object object>, metadata=None)# Removes an existing snapshot. Snapshots are used in <a href=”https://cloud.google.com/pubsub/docs/replay-overview”>Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.<br><br> When the snapshot is deleted, all messages retained in the snapshot are immediately dropped. After a snapshot is deleted, a new one may be created with the same name, but the new one has no association with the old snapshot or its subscription, unless the same subscription is specified.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> snapshot = client.snapshot_path('[PROJECT]', '[SNAPSHOT]') >>> >>> client.delete_snapshot(snapshot)
- Parameters
snapshot (str) – The name of the snapshot to delete. Format is
projects/{project}/snapshots/{snap}
.retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
delete_subscription
(subscription, retry=<object object>, timeout=<object object>, metadata=None)# Deletes an existing subscription. All messages retained in the subscription are immediately dropped. Calls to
Pull
after deletion will returnNOT_FOUND
. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription or its topic unless the same topic is specified.Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> client.delete_subscription(subscription)
- Parameters
subscription (str) – The subscription to delete. Format is
projects/{project}/subscriptions/{sub}
.retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
classmethod
from_service_account_file
(filename, **kwargs)[source]# Creates an instance of this client using the provided credentials file.
-
classmethod
from_service_account_json
(filename, **kwargs)# Creates an instance of this client using the provided credentials file.
-
get_iam_policy
(resource, options_=None, retry=<object object>, timeout=<object object>, metadata=None)# Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.get_iam_policy(resource)
- Parameters
resource (str) – REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
options_ (Union[dict, GetPolicyOptions]) –
OPTIONAL: A
GetPolicyOptions
object for specifying options toGetIamPolicy
. This field is only used by Cloud IAM.If a dict is provided, it must be of the same form as the protobuf message
GetPolicyOptions
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
Policy
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
get_subscription
(subscription, retry=<object object>, timeout=<object object>, metadata=None)# Gets the configuration details of a subscription.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.get_subscription(subscription)
- Parameters
subscription (str) – The name of the subscription to get. Format is
projects/{project}/subscriptions/{sub}
.retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
Subscription
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
list_snapshots
(project, page_size=None, retry=<object object>, timeout=<object object>, metadata=None)# Lists the existing snapshots. Snapshots are used in <a href=”https://cloud.google.com/pubsub/docs/replay-overview”>Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> project = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_snapshots(project): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_snapshots(project).pages: ... for element in page: ... # process element ... pass
- Parameters
project (str) – The name of the project in which to list snapshots. Format is
projects/{project-id}
.page_size (int) – The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page.
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
GRPCIterator
instance. An iterable ofSnapshot
instances. You can also iterate over the pages of the response using its pages property.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
list_subscriptions
(project, page_size=None, retry=<object object>, timeout=<object object>, metadata=None)# Lists matching subscriptions.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> project = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_subscriptions(project): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_subscriptions(project).pages: ... for element in page: ... # process element ... pass
- Parameters
project (str) – The name of the project in which to list subscriptions. Format is
projects/{project-id}
.page_size (int) – The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page.
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
GRPCIterator
instance. An iterable ofSubscription
instances. You can also iterate over the pages of the response using its pages property.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
modify_ack_deadline
(subscription, ack_ids, ack_deadline_seconds, retry=<object object>, timeout=<object object>, metadata=None)# Modifies the ack deadline for a specific message. This method is useful to indicate that more time is needed to process a message by the subscriber, or to make the message available for redelivery if the processing was interrupted. Note that this does not modify the subscription-level
ackDeadlineSeconds
used for subsequent messages.Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> # TODO: Initialize `ack_ids`: >>> ack_ids = [] >>> >>> # TODO: Initialize `ack_deadline_seconds`: >>> ack_deadline_seconds = 0 >>> >>> client.modify_ack_deadline(subscription, ack_ids, ack_deadline_seconds)
- Parameters
subscription (str) – The name of the subscription. Format is
projects/{project}/subscriptions/{sub}
.ack_deadline_seconds (int) – The new ack deadline with respect to the time this request was sent to the Pub/Sub system. For example, if the value is 10, the new ack deadline will expire 10 seconds after the
ModifyAckDeadline
call was made. Specifying zero might immediately make the message available for delivery to another subscriber client. This typically results in an increase in the rate of message redeliveries (that is, duplicates). The minimum deadline you can specify is 0 seconds. The maximum deadline you can specify is 600 seconds (10 minutes).retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
modify_push_config
(subscription, push_config, retry=<object object>, timeout=<object object>, metadata=None)# Modifies the
PushConfig
for a specified subscription.This may be used to change a push subscription to a pull one (signified by an empty
PushConfig
) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to thePushConfig
.Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> # TODO: Initialize `push_config`: >>> push_config = {} >>> >>> client.modify_push_config(subscription, push_config)
- Parameters
subscription (str) – The name of the subscription. Format is
projects/{project}/subscriptions/{sub}
.push_config (Union[dict, PushConfig]) –
The push configuration for future deliveries.
An empty
pushConfig
indicates that the Pub/Sub system should stop pushing messages from the given subscription and allow messages to be pulled and acknowledged - effectively pausing the subscription ifPull
orStreamingPull
is not called.If a dict is provided, it must be of the same form as the protobuf message
PushConfig
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
static
project_path
(project)# Return a fully-qualified project string.
-
pull
(subscription, max_messages, return_immediately=None, retry=<object object>, timeout=<object object>, metadata=None)# Pulls messages from the server. The server may return
UNAVAILABLE
if there are too many concurrent pull requests pending for the given subscription.Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> # TODO: Initialize `max_messages`: >>> max_messages = 0 >>> >>> response = client.pull(subscription, max_messages)
- Parameters
subscription (str) – The subscription from which messages should be pulled. Format is
projects/{project}/subscriptions/{sub}
.max_messages (int) – The maximum number of messages to return for this request. Must be a positive integer. The Pub/Sub system may return fewer than the number specified.
return_immediately (bool) – If this field set to true, the system will respond immediately even if it there are no messages available to return in the
Pull
response. Otherwise, the system may wait (for a bounded amount of time) until at least one message is available, rather than returning no messages.retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
PullResponse
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
seek
(subscription, time=None, snapshot=None, retry=<object object>, timeout=<object object>, metadata=None)# Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided in the request. Snapshots are used in <a href=”https://cloud.google.com/pubsub/docs/replay-overview”>Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. Note that both the subscription and the snapshot must be on the same topic.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.seek(subscription)
- Parameters
subscription (str) – The subscription to affect.
time (Union[dict, Timestamp]) –
The time to seek to. Messages retained in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged. Note that this operation affects only those messages retained in the subscription (configured by the combination of
message_retention_duration
andretain_acked_messages
). For example, iftime
corresponds to a point before the message retention window (or to a point before the system’s notion of the subscription creation time), only retained messages will be marked as unacknowledged, and already-expunged messages will not be restored.If a dict is provided, it must be of the same form as the protobuf message
Timestamp
snapshot (str) – The snapshot to seek to. The snapshot’s topic must be the same as that of the provided subscription. Format is
projects/{project}/snapshots/{snap}
.retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
SeekResponse
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
set_iam_policy
(resource, policy, retry=<object object>, timeout=<object object>, metadata=None)# Sets the access control policy on the specified resource. Replaces any existing policy.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> # TODO: Initialize `policy`: >>> policy = {} >>> >>> response = client.set_iam_policy(resource, policy)
- Parameters
resource (str) – REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
policy (Union[dict, Policy]) –
REQUIRED: The complete policy to be applied to the
resource
. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them.If a dict is provided, it must be of the same form as the protobuf message
Policy
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
Policy
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
static
snapshot_path
(project, snapshot)# Return a fully-qualified snapshot string.
-
streaming_pull
(requests, retry=<object object>, timeout=<object object>, metadata=None)# Establishes a stream with the server, which sends messages down to the client. The client streams acknowledgements and ack deadline modifications back to the server. The server will close the stream and return the status on any error. The server may close the stream with status
UNAVAILABLE
to reassign server-side resources, in which case, the client should re-establish the stream. Flow control can be achieved by configuring the underlying RPC channel.EXPERIMENTAL: This method interface might change in the future.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> # TODO: Initialize `stream_ack_deadline_seconds`: >>> stream_ack_deadline_seconds = 0 >>> request = {'subscription': subscription, 'stream_ack_deadline_seconds': stream_ack_deadline_seconds} >>> >>> requests = [request] >>> for element in client.streaming_pull(requests): ... # process element ... pass
- Parameters
requests (iterator[dict|google.cloud.pubsub_v1.proto.pubsub_pb2.StreamingPullRequest]) – The input objects. If a dict is provided, it must be of the same form as the protobuf message
StreamingPullRequest
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
Iterable[~google.cloud.pubsub_v1.types.StreamingPullResponse].
- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
subscribe
(subscription, callback, flow_control=(), scheduler=None)[source]# Asynchronously start receiving messages on a given subscription.
This method starts a background thread to begin pulling messages from a Pub/Sub subscription and scheduling them to be processed using the provided
callback
.The
callback
will be called with an individualgoogle.cloud.pubsub_v1.subscriber.message.Message
. It is the responsibility of the callback to either callack()
ornack()
on the message when it finished processing. If an exception occurs in the callback during processing, the exception is logged and the message isnack()
ed.The
flow_control
argument can be used to control the rate of at which messages are pulled. The settings are relatively conservative by default to prevent “message hoarding” - a situation where the client pulls a large number of messages but can not process them fast enough leading it to “starve” other clients of messages. Increasing these settings may lead to faster throughput for messages that do not take a long time to process.This method starts the receiver in the background and returns a Future representing its execution. Waiting on the future (calling
result()
) will block forever or until a non-recoverable error is encountered (such as loss of network connectivity). Cancelling the future will signal the process to shutdown gracefully and exit.Note
This uses Pub/Sub’s streaming pull feature. This feature properties that may be surprising. Please take a look at https://cloud.google.com/pubsub/docs/pull#streamingpull for more details on how streaming pull behaves compared to the synchronous pull method.
Example:
from google.cloud import pubsub_v1 subscriber_client = pubsub_v1.SubscriberClient() # existing subscription subscription = subscriber_client.subscription_path( 'my-project-id', 'my-subscription') def callback(message): print(message) message.ack() future = subscriber_client.subscribe( subscription, callback) try: future.result() except KeyboardInterrupt: future.cancel()
- Parameters
subscription (str) – The name of the subscription. The subscription should have already been created (for example, by using
create_subscription()
).callback (Callable[Message]) – The callback function. This function receives the message as its only argument and will be called from a different thread/ process depending on the scheduling strategy.
flow_control (FlowControl) – The flow control settings. Use this to prevent situations where you are inundated with too many messages at once.
scheduler (Scheduler) – An optional scheduler to use when executing the callback. This controls how callbacks are executed concurrently.
- Returns
A
StreamingPullFuture
instance that can be used to manage the background stream.
-
static
subscription_path
(project, subscription)# Return a fully-qualified subscription string.
-
property
target
# Return the target (where the API is).
- Returns
The location of the API.
- Return type
-
test_iam_permissions
(resource, permissions, retry=<object object>, timeout=<object object>, metadata=None)# Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.
Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may “fail open” without warning.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] >>> >>> response = client.test_iam_permissions(resource, permissions)
- Parameters
resource (str) – REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
permissions (list[str]) – The set of permissions to check for the
resource
. Permissions with wildcards (such as ‘*’ or ‘storage.*’) are not allowed. For more information see IAM Overview.retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
TestIamPermissionsResponse
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
static
topic_path
(project, topic)# Return a fully-qualified topic string.
-
update_snapshot
(snapshot, update_mask, retry=<object object>, timeout=<object object>, metadata=None)# Updates an existing snapshot. Snapshots are used in <a href=”https://cloud.google.com/pubsub/docs/replay-overview”>Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> seconds = 123456 >>> expire_time = {'seconds': seconds} >>> snapshot = {'expire_time': expire_time} >>> paths_element = 'expire_time' >>> paths = [paths_element] >>> update_mask = {'paths': paths} >>> >>> response = client.update_snapshot(snapshot, update_mask)
- Parameters
snapshot (Union[dict, Snapshot]) –
The updated snapshot object.
If a dict is provided, it must be of the same form as the protobuf message
Snapshot
update_mask (Union[dict, FieldMask]) –
Indicates which fields in the provided snapshot to update. Must be specified and non-empty.
If a dict is provided, it must be of the same form as the protobuf message
FieldMask
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
Snapshot
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.
-
update_subscription
(subscription, update_mask, retry=<object object>, timeout=<object object>, metadata=None)# Updates an existing subscription. Note that certain properties of a subscription, such as its topic, are not modifiable.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> ack_deadline_seconds = 42 >>> subscription = {'ack_deadline_seconds': ack_deadline_seconds} >>> paths_element = 'ack_deadline_seconds' >>> paths = [paths_element] >>> update_mask = {'paths': paths} >>> >>> response = client.update_subscription(subscription, update_mask)
- Parameters
subscription (Union[dict, Subscription]) –
The updated subscription object.
If a dict is provided, it must be of the same form as the protobuf message
Subscription
update_mask (Union[dict, FieldMask]) –
Indicates which fields in the provided subscription to update. Must be specified and non-empty.
If a dict is provided, it must be of the same form as the protobuf message
FieldMask
retry (Optional[google.api_core.retry.Retry]) – A retry object used to retry requests. If
None
is specified, requests will be retried using a default configuration.timeout (Optional[float]) – The amount of time, in seconds, to wait for the request to complete. Note that if
retry
is specified, the timeout applies to each individual attempt.metadata (Optional[Sequence[Tuple[str, str]]]) – Additional metadata that is provided to the method.
- Returns
A
Subscription
instance.- Raises
google.api_core.exceptions.GoogleAPICallError – If the request failed for any reason.
google.api_core.exceptions.RetryError – If the request failed due to a retryable error and retry attempts failed.
ValueError – If the parameters are invalid.