As of January 1, 2020 this library no longer supports Python 2 on the latest released version. Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.

Publisher Client API (v1)

class google.cloud.pubsub_v1.publisher.client.Client(batch_settings=(), publisher_options=(), **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.

  • publisher_options (PublisherOptions) – The options for the publisher client. Note that enabling message ordering will override the publish retry timeout to be infinite.

  • 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. Regional endpoints can be set via client_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
    publisher_options = pubsub_v1.types.PublisherOptions(
        enable_message_ordering=False,
        flow_control=pubsub_v1.types.PublishFlowControl(
            message_limit=2000,
            limit_exceeded_behavior=pubsub_v1.types.LimitExceededBehavior.BLOCK,
        ),
    ),

    # Optional
    client_options = {
        "api_endpoint": REGIONAL_ENDPOINT
    }
)
static common_billing_account_path(billing_account: str)str

Returns a fully-qualified billing_account string.

static common_folder_path(folder: str)str

Returns a fully-qualified folder string.

static common_location_path(project: str, location: str)str

Returns a fully-qualified location string.

static common_organization_path(organization: str)str

Returns a fully-qualified organization string.

static common_project_path(project: str)str

Returns a fully-qualified project string.

create_topic(request: google.cloud.pubsub_v1.types.Topic = None, *, name: str = None, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.cloud.pubsub_v1.types.Topic

Creates the given topic with the given name. See the [resource name rules] (https://cloud.google.com/pubsub/docs/admin#resource_names).

Parameters
  • request (google.pubsub_v1.types.Topic) – The request object. A topic resource.

  • name (str) –

    Required. 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".

    This corresponds to the name field on the request instance; if request is provided, this should not be set.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

A topic resource.

Return type

google.pubsub_v1.types.Topic

delete_topic(request: google.cloud.pubsub_v1.types.DeleteTopicRequest = None, *, topic: str = None, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())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_.

Parameters
  • request (google.pubsub_v1.types.DeleteTopicRequest) – The request object. Request for the DeleteTopic method.

  • topic (str) –

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

    This corresponds to the topic field on the request instance; if request is provided, this should not be set.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

detach_subscription(request: google.cloud.pubsub_v1.types.DetachSubscriptionRequest = None, *, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.cloud.pubsub_v1.types.DetachSubscriptionResponse

Detaches a subscription from this topic. All messages retained in the subscription are dropped. Subsequent Pull and StreamingPull requests will return FAILED_PRECONDITION. If the subscription is a push subscription, pushes to the endpoint will stop.

Parameters
  • request (google.pubsub_v1.types.DetachSubscriptionRequest) – The request object. Request for the DetachSubscription method.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

Response for the DetachSubscription method. Reserved for future use.

Return type

google.pubsub_v1.types.DetachSubscriptionResponse

ensure_cleanup_and_commit_timer_runs()[source]

Ensure a cleanup/commit timer thread is running.

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

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.

static from_service_account_info(info: dict, *args, **kwargs)
Creates an instance of this client using the provided credentials

info.

Parameters
  • info (dict) – The service account private key info.

  • args – Additional arguments to pass to the constructor.

  • kwargs – Additional arguments to pass to the constructor.

Returns

The constructed client.

Return type

PublisherClient

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(request: google.iam.v1.iam_policy_pb2.GetIamPolicyRequest = None, *, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.iam.v1.policy_pb2.Policy

Gets the IAM access control policy for a function.

Returns an empty policy if the function exists and does not have a policy set.

Parameters
  • request (GetIamPolicyRequest) – The request object. Request message for GetIamPolicy method.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. A Policy is a collection of bindings. A binding binds one or more members to a single role. Members can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions (defined by IAM or configured by users). A binding can optionally specify a condition, which is a logic expression that further constrains the role binding based on attributes about the request and/or target resource.

JSON Example:

{
  "bindings": [
    {
      "role": "roles/resourcemanager.organizationAdmin",
      "members": [
        "user:mike@example.com",
        "group:admins@example.com",
        "domain:google.com",
        "serviceAccount:my-project-id@appspot.gserviceaccount.com"
      ]
    },
    {
      "role": "roles/resourcemanager.organizationViewer",
      "members": ["user:eve@example.com"],
      "condition": {
        "title": "expirable access",
        "description": "Does not grant access after Sep 2020",
        "expression": "request.time <
        timestamp('2020-10-01T00:00:00.000Z')",
      }
    }
  ]
}

YAML Example:

bindings:
- members:
  - user:mike@example.com
  - group:admins@example.com
  - domain:google.com
  - serviceAccount:my-project-id@appspot.gserviceaccount.com
  role: roles/resourcemanager.organizationAdmin
- members:
  - user:eve@example.com
  role: roles/resourcemanager.organizationViewer
  condition:
    title: expirable access
    description: Does not grant access after Sep 2020
    expression: request.time < timestamp('2020-10-01T00:00:00.000Z')

For a description of IAM and its features, see the IAM developer’s guide.

Return type

Policy

get_topic(request: google.cloud.pubsub_v1.types.GetTopicRequest = None, *, topic: str = None, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.cloud.pubsub_v1.types.Topic

Gets the configuration of a topic.

Parameters
  • request (google.pubsub_v1.types.GetTopicRequest) – The request object. Request for the GetTopic method.

  • topic (str) –

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

    This corresponds to the topic field on the request instance; if request is provided, this should not be set.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

A topic resource.

Return type

google.pubsub_v1.types.Topic

list_topic_snapshots(request: google.cloud.pubsub_v1.types.ListTopicSnapshotsRequest = None, *, topic: str = None, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager

Lists the names of the snapshots on this topic. 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.

Parameters
  • request (google.pubsub_v1.types.ListTopicSnapshotsRequest) – The request object. Request for the ListTopicSnapshots method.

  • topic (str) –

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

    This corresponds to the topic field on the request instance; if request is provided, this should not be set.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

Response for the ListTopicSnapshots method.

Iterating over this object will yield results and resolve additional pages automatically.

Return type

google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager

list_topic_subscriptions(request: google.cloud.pubsub_v1.types.ListTopicSubscriptionsRequest = None, *, topic: str = None, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager

Lists the names of the attached subscriptions on this topic.

Parameters
  • request (google.pubsub_v1.types.ListTopicSubscriptionsRequest) – The request object. Request for the ListTopicSubscriptions method.

  • topic (str) –

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

    This corresponds to the topic field on the request instance; if request is provided, this should not be set.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

Response for the ListTopicSubscriptions method.

Iterating over this object will yield results and resolve additional pages automatically.

Return type

google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager

list_topics(request: google.cloud.pubsub_v1.types.ListTopicsRequest = None, *, project: str = None, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.pubsub_v1.services.publisher.pagers.ListTopicsPager

Lists matching topics.

Parameters
  • request (google.pubsub_v1.types.ListTopicsRequest) – The request object. Request for the ListTopics method.

  • project (str) –

    Required. The name of the project in which to list topics. Format is projects/{project-id}.

    This corresponds to the project field on the request instance; if request is provided, this should not be set.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

Response for the ListTopics method.

Iterating over this object will yield results and resolve additional pages automatically.

Return type

google.pubsub_v1.services.publisher.pagers.ListTopicsPager

static parse_common_billing_account_path(path: str)Dict[str, str]

Parse a billing_account path into its component segments.

static parse_common_folder_path(path: str)Dict[str, str]

Parse a folder path into its component segments.

static parse_common_location_path(path: str)Dict[str, str]

Parse a location path into its component segments.

static parse_common_organization_path(path: str)Dict[str, str]

Parse a organization path into its component segments.

static parse_common_project_path(path: str)Dict[str, str]

Parse a project path into its component segments.

static parse_schema_path(path: str)Dict[str, str]

Parses a schema path into its component segments.

static parse_subscription_path(path: str)Dict[str, str]

Parses a subscription path into its component segments.

static parse_topic_path(path: str)Dict[str, str]

Parses a topic path into its component segments.

publish(topic, data, ordering_key='', retry=<object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, **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. This method may block if LimitExceededBehavior.BLOCK is used in the flow control settings.

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
  • topic (str) – The topic to publish messages to.

  • data (bytes) – A bytestring representing the message body. This must be a bytestring.

  • ordering_key – A string that identifies related messages for which publish order should be respected. Message ordering must be enabled for this client to use this feature.

  • retry (Optional[google.api_core.retry.Retry]) – Designation of what errors, if any, should be retried. If ordering_key is specified, the total retry deadline will be changed to “infinity”. If given, it overides any retry passed into the client through the publisher_options argument.

  • timeout (TimeoutType) – The timeout for the RPC request. Can be used to override any timeout passed in through publisher_options when instantiating the client.

  • attrs (Mapping[str, str]) – A dictionary of attributes to be sent as metadata. (These may be text strings or byte strings.)

Returns

A Future instance that conforms to Python Standard library’s Future interface (but not an instance of that class).

Raises
  • RuntimeError – If called after publisher has been stopped by a stop() method call.

  • pubsub_v1.publisher.exceptions.MessageTooLargeError – If publishing the message would exceed the max size limit on the backend.

resume_publish(topic, ordering_key)[source]

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

Parameters
  • topic (str) – The topic to publish messages to.

  • ordering_key – A string that identifies related messages for which publish order should be respected.

Raises
  • RuntimeError – If called after publisher has been stopped by a stop() method call.

  • ValueError – If the topic/ordering key combination has not been seen before by this client.

static schema_path(project: str, schema: str)str

Returns a fully-qualified schema string.

set_iam_policy(request: google.iam.v1.iam_policy_pb2.SetIamPolicyRequest = None, *, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.iam.v1.policy_pb2.Policy

Sets the IAM access control policy on the specified function.

Replaces any existing policy.

Parameters
  • request (SetIamPolicyRequest) – The request object. Request message for SetIamPolicy method.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. A Policy is a collection of bindings. A binding binds one or more members to a single role. Members can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions (defined by IAM or configured by users). A binding can optionally specify a condition, which is a logic expression that further constrains the role binding based on attributes about the request and/or target resource.

JSON Example:

{
  "bindings": [
    {
      "role": "roles/resourcemanager.organizationAdmin",
      "members": [
        "user:mike@example.com",
        "group:admins@example.com",
        "domain:google.com",
        "serviceAccount:my-project-id@appspot.gserviceaccount.com"
      ]
    },
    {
      "role": "roles/resourcemanager.organizationViewer",
      "members": ["user:eve@example.com"],
      "condition": {
        "title": "expirable access",
        "description": "Does not grant access after Sep 2020",
        "expression": "request.time <
        timestamp('2020-10-01T00:00:00.000Z')",
      }
    }
  ]
}

YAML Example:

bindings:
- members:
  - user:mike@example.com
  - group:admins@example.com
  - domain:google.com
  - serviceAccount:my-project-id@appspot.gserviceaccount.com
  role: roles/resourcemanager.organizationAdmin
- members:
  - user:eve@example.com
  role: roles/resourcemanager.organizationViewer
  condition:
    title: expirable access
    description: Does not grant access after Sep 2020
    expression: request.time < timestamp('2020-10-01T00:00:00.000Z')

For a description of IAM and its features, see the IAM developer’s guide.

Return type

Policy

stop()[source]

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.

Note

This method is non-blocking. Use Future() objects returned by publish() to make sure all publish requests completed, either in success or error.

Raises

RuntimeError – If called after publisher has been stopped by a stop() method call.

static subscription_path(project: str, subscription: str)str

Returns a fully-qualified subscription string.

property target

Return the target (where the API is).

Returns

The location of the API.

Return type

str

test_iam_permissions(request: google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest = None, *, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse
Tests the specified IAM permissions against the IAM access control

policy for a function.

If the function does not exist, this will return an empty set of permissions, not a NOT_FOUND error.

Parameters
  • request (TestIamPermissionsRequest) – The request object. Request message for TestIamPermissions method.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

Response message for TestIamPermissions method.

Return type

TestIamPermissionsResponse

static topic_path(project: str, topic: str)str

Returns a fully-qualified topic string.

update_topic(request: google.cloud.pubsub_v1.types.UpdateTopicRequest = None, *, retry: google.api_core.retry.Retry = <object object>, timeout: Union[int, float, google.api_core.timeout.ConstantTimeout, google.api_core.timeout.ExponentialTimeout] = <object object>, metadata: Sequence[Tuple[str, str]] = ())google.cloud.pubsub_v1.types.Topic

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

Parameters
  • request (google.pubsub_v1.types.UpdateTopicRequest) – The request object. Request for the UpdateTopic method.

  • retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried.

  • timeout (TimeoutType) – The timeout for this request.

  • metadata (Sequence[Tuple[str, str]]) – Strings which should be sent along with the request as metadata.

Returns

A topic resource.

Return type

google.pubsub_v1.types.Topic