Publisher Client API#
-
class
google.cloud.pubsub_v1.publisher.client.
Client
(batch_settings=(), **kwargs)[source]# 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
batch_settings (BatchSettings) – The settings for batch publishing.
kwargs (dict) – 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 viaclient_config
where user-provided retry configurations are applied to default retry settings. And 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 publisher_client = pubsub_v1.PublisherClient( # Optional batch_settings = pubsub_v1.types.BatchSettings( max_bytes=1024, # One kilobyte max_latency=1, # One second ), # Optional client_config = { "interfaces": { "google.pubsub.v1.Publisher": { "retry_params": { "messaging": { 'total_timeout_millis': 650000, # default: 600000 } } } } }, # Optional client_options = { "api_endpoint": REGIONAL_ENDPOINT } )
-
create_topic
(name, labels=None, message_storage_policy=None, kms_key_name=None, retry=<object object>, timeout=<object object>, metadata=None)# Creates the given topic with the given name. See the resource name rules.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.PublisherClient() >>> >>> name = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.create_topic(name)
- Parameters
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 (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with “goog”.
labels (dict[str -> str]) – See <a href=”https://cloud.google.com/pubsub/docs/labels”> Creating and managing labels</a>.
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.
- Returns
A
Topic
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_topic
(topic, retry=<object object>, timeout=<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 theirtopic
field is set to_deleted-topic_
.Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.PublisherClient() >>> >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> client.delete_topic(topic)
- Parameters
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.
- 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, batch_settings=(), **kwargs)[source]# Creates an instance of this client using the provided credentials file.
- Parameters
filename (str) – The path to the service account private key json file.
batch_settings (BatchSettings) – The settings for batch publishing.
kwargs – Additional arguments to pass to the constructor.
- Returns
A Publisher
Client
instance that is the constructed client.
-
classmethod
from_service_account_json
(filename, batch_settings=(), **kwargs)# Creates an instance of this client using the provided credentials file.
- Parameters
filename (str) – The path to the service account private key json file.
batch_settings (BatchSettings) – The settings for batch publishing.
kwargs – Additional arguments to pass to the constructor.
- Returns
A Publisher
Client
instance that is the constructed client.
-
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.PublisherClient() >>> >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> 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_topic
(topic, retry=<object object>, timeout=<object object>, metadata=None)# Gets the configuration of a topic.
Example
>>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.PublisherClient() >>> >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.get_topic(topic)
- Parameters
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.
- Returns
A
Topic
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_topic_subscriptions
(topic, page_size=None, retry=<object object>, timeout=<object object>, metadata=None)# Lists the names of the subscriptions on this topic.
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
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.
- Returns
A
GRPCIterator
instance. An iterable ofstr
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_topics
(project, page_size=None, retry=<object object>, timeout=<object object>, metadata=None)# Lists matching topics.
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
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.
- Returns
A
GRPCIterator
instance. An iterable ofTopic
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.
-
static
project_path
(project)# Return a fully-qualified project string.
-
publish
(topic, data, **attrs)[source]# Publish a single message.
Note
Messages in Pub/Sub are blobs of bytes. They are binary data, not text. You must send data as a bytestring (
bytes
in Python 3;str
in Python 2), and this library will raise an exception if you send a text string.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.
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')
-
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.PublisherClient() >>> >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> # 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.
-
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.PublisherClient() >>> >>> resource = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> # 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_topic
(topic, update_mask, retry=<object object>, timeout=<object object>, metadata=None)# Updates an existing topic. Note that certain properties of a topic are not modifiable.
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
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. Themessage_storage_policy
must not be set in thetopic
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.
- Returns
A
Topic
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.