Class Client (1.3.1)

Client(batch_settings=(), publisher_options=(), **kwargs)

A publisher client for Google Cloud Pub/Sub.

This creates an object that is capable of publishing messages. Generally, you can instantiate this client with no arguments, and you get sensible defaults.

Parameters

NameDescription
kwargs dict Example: .. code-block:: python from google.cloud import pubsub_v1 publisher_client = pubsub_v1.PublisherClient( # Optional batch_settings = pubsub_v1.types.BatchSettings( max_bytes=1024, # One kilobyte max_latency=1, # One second ), # Optional publisher_options = pubsub_v1.types.PublisherOptions( enable_message_ordering=False ), # Optional client_config = { "interfaces": { "google.pubsub.v1.Publisher": { "retry_params": { "messaging": { 'total_timeout_millis': 650000, # default: 600000 } } } } }, # Optional client_options = { "api_endpoint": REGIONAL_ENDPOINT } )

Any additional arguments provided are sent as keyword arguments to the underlying PublisherClient. Generally you should not need to set additional keyword arguments. Optionally, publish retry settings can be set via client_config where user-provided retry configurations are applied to default retry settings. And regional endpoints can be set via client_options that takes a single key-value pair that defines the endpoint.

batch_settings BatchSettings

The settings for batch publishing.

publisher_options PublisherOptions

The options for the publisher client. Note that enabling message ordering will override the publish retry timeout to be infinite.

Properties

target

Return the target (where the API is).

Returns
TypeDescription
strThe location of the API.

Methods

create_topic

create_topic(name, labels=None, message_storage_policy=None, kms_key_name=None, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <object object>>, metadata=None)

Creates the given topic with the given name. See the resource name rules.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

name = client.topic_path('[PROJECT]', '[TOPIC]')

response = client.create_topic(name)

Parameters
NameDescription
name str

The name of the topic. It must have the format "projects/{project}/topics/{topic}". {topic} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9]), dashes (-), underscores (_), periods (.), tildes (``<code>), plus (</code>+<code>) or percent signs (</code>%<code>). It must be between 3 and 255 characters in length, and it must not start with </code>"goog".

labels dict[str -> str]

See Creating and managing labels.

message_storage_policy Union[dict, MessageStoragePolicy]

Policy constraining the set of Google Cloud Platform regions where messages published to the topic may be stored. If not present, then no constraints are in effect. If a dict is provided, it must be of the same form as the protobuf message MessageStoragePolicy

kms_key_name str

The resource name of the Cloud KMS CryptoKey to be used to protect access to messages published on this topic. The expected format is projects//locations//keyRings//cryptoKeys/.

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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

delete_topic

delete_topic(topic, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <object object>>, metadata=None)

Deletes the topic with the given name. Returns NOT_FOUND if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their topic field is set to _deleted-topic_.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

topic = client.topic_path('[PROJECT]', '[TOPIC]')

client.delete_topic(topic)

Parameters
NameDescription
topic str

Name of the topic to delete. Format is projects/{project}/topics/{topic}.

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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

ensure_cleanup_and_commit_timer_runs

ensure_cleanup_and_commit_timer_runs()

Ensure a cleanup/commit timer thread is running.

If a cleanup/commit timer thread is already running, this does nothing.

from_service_account_file

from_service_account_file(filename, batch_settings=(), **kwargs)

Creates an instance of this client using the provided credentials file.

Parameters
NameDescription
filename str

The path to the service account private key json file.

batch_settings BatchSettings

The settings for batch publishing.

from_service_account_json

from_service_account_json(filename, batch_settings=(), **kwargs)

Creates an instance of this client using the provided credentials file.

Parameters
NameDescription
filename str

The path to the service account private key json file.

batch_settings BatchSettings

The settings for batch publishing.

get_iam_policy

get_iam_policy(resource, options_=None, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <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.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

resource = client.topic_path('[PROJECT]', '[TOPIC]')

response = client.get_iam_policy(resource)

Parameters
NameDescription
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 to GetIamPolicy. 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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

get_topic

get_topic(topic, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <object object>>, metadata=None)

Gets the configuration of a topic.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

topic = client.topic_path('[PROJECT]', '[TOPIC]')

response = client.get_topic(topic)

Parameters
NameDescription
topic str

The name of the topic to get. Format is projects/{project}/topics/{topic}.

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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

list_topic_subscriptions

list_topic_subscriptions(topic, page_size=None, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <object object>>, metadata=None)

Lists the names of the subscriptions on this topic.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

topic = client.topic_path('[PROJECT]', '[TOPIC]')

Iterate over all results

for element in client.list_topic_subscriptions(topic): ... # process element ... pass

Alternatively:

Iterate over results one page at a time

for page in client.list_topic_subscriptions(topic).pages: ... for element in page: ... # process element ... pass

Parameters
NameDescription
topic str

The name of the topic that subscriptions are attached to. Format is projects/{project}/topics/{topic}.

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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

list_topics

list_topics(project, page_size=None, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <object object>>, metadata=None)

Lists matching topics.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

project = client.project_path('[PROJECT]')

Iterate over all results

for element in client.list_topics(project): ... # process element ... pass

Alternatively:

Iterate over results one page at a time

for page in client.list_topics(project).pages: ... for element in page: ... # process element ... pass

Parameters
NameDescription
project str

The name of the project in which to list topics. 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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

project_path

project_path(project)

Return a fully-qualified project string.

publish

publish(topic, data, ordering_key="", **attrs)

Publish a single message.

The reason that this is so important (and why we do not try to coerce for you) is because Pub/Sub is also platform independent and there is no way to know how to decode messages properly on the other side; therefore, encoding and decoding is a required exercise for the developer.

Add the given message to this object; this will cause it to be published once the batch either has enough messages or a sufficient period of time has elapsed.

.. rubric:: Example

from google.cloud import pubsub_v1 client = pubsub_v1.PublisherClient() topic = client.topic_path('[PROJECT]', '[TOPIC]') data = b'The rain in Wales falls mainly on the snails.' response = client.publish(topic, data, username='guido')

Parameters
NameDescription
attrs Mapping[str, str]

A dictionary of attributes to be sent as metadata. (These may be text strings or byte strings.)

topic str

The topic to publish messages to.

data bytes

A bytestring representing the message body. This must be a bytestring.

Exceptions
TypeDescription
RuntimeErrorIf called after publisher has been stopped by a stop() method call.
pubsub_v1.publisher.exceptions.MessageTooLargeErrorIf publishing the message would exceed the max size limit on the backend.

resume_publish

resume_publish(topic, ordering_key)

Resume publish on an ordering key that has had unrecoverable errors.

Parameter
NameDescription
topic str

The topic to publish messages to.

Exceptions
TypeDescription
RuntimeErrorIf called after publisher has been stopped by a stop() method call.
ValueErrorIf the topic/ordering key combination has not been seen before by this client.

set_iam_policy

set_iam_policy(resource, policy, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <object object>>, metadata=None)

Sets the access control policy on the specified resource. Replaces any existing policy.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

resource = client.topic_path('[PROJECT]', '[TOPIC]')

TODO: Initialize policy:

policy = {}

response = client.set_iam_policy(resource, policy)

Parameters
NameDescription
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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

stop

stop()

Immediately publish all outstanding messages.

Asynchronously sends all outstanding messages and prevents future calls to publish(). Method should be invoked prior to deleting this Client() object in order to ensure that no pending messages are lost.

Exceptions
TypeDescription
RuntimeErrorIf called after publisher has been stopped by a stop() method call.

test_iam_permissions

test_iam_permissions(resource, permissions, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <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.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

resource = client.topic_path('[PROJECT]', '[TOPIC]')

TODO: Initialize permissions:

permissions = []

response = client.test_iam_permissions(resource, permissions)

Parameters
NameDescription
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 https://cloud.google.com/iam/docs/overview#permissions__.

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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.

topic_path

topic_path(project, topic)

Return a fully-qualified topic string.

update_topic

update_topic(topic, update_mask, retry=<_MethodDefault._DEFAULT_VALUE: <object object>>, timeout=<_MethodDefault._DEFAULT_VALUE: <object object>>, metadata=None)

Updates an existing topic. Note that certain properties of a topic are not modifiable.

.. rubric:: Example

from google.cloud import pubsub_v1

client = pubsub_v1.PublisherClient()

TODO: Initialize topic:

topic = {}

TODO: Initialize update_mask:

update_mask = {}

response = client.update_topic(topic, update_mask)

Parameters
NameDescription
topic Union[dict, Topic]

The updated topic object. If a dict is provided, it must be of the same form as the protobuf message Topic

update_mask Union[dict, FieldMask]

Indicates which fields in the provided topic to update. Must be specified and non-empty. Note that if update_mask contains "message_storage_policy" then the new value will be determined based on the policy configured at the project or organization level. The message_storage_policy must not be set in the topic provided above. 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.

Exceptions
TypeDescription
google.api_core.exceptions.GoogleAPICallErrorIf the request failed for any reason.
google.api_core.exceptions.RetryErrorIf the request failed due to a retryable error and retry attempts failed.
ValueErrorIf the parameters are invalid.