Topics#

Define API Topics.

class google.cloud.pubsub.topic.Topic(name, client, timestamp_messages=False)[source]#

Bases: object

Topics are targets to which messages can be published.

Subscribers then receive those messages.

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics

Parameters:
  • name (str) – the name of the topic
  • client (google.cloud.pubsub.client.Client) – A client which holds credentials and project configuration for the topic (which requires a project).
  • timestamp_messages (bool) – If true, the topic will add a timestamp key to the attributes of each published message: the value will be an RFC 3339 timestamp.
subscription(name, ack_deadline=None, push_endpoint=None, retain_acked_messages=None, message_retention_duration=None)[source]#

Creates a subscription bound to the current topic.

Example: pull-mode subcription, default paramter values

    sub_defaults = topic.subscription(SUB_DEFAULTS)

Example: pull-mode subcription, override ack_deadline default

    sub_ack90 = topic.subscription(SUB_ACK90, ack_deadline=90)

Example: push-mode subcription

    subscription = topic.subscription(SUB_PUSH, push_endpoint=PUSH_URL)
    subscription.create()               # API request
Parameters:
  • name (str) – the name of the subscription
  • ack_deadline (int) – the deadline (in seconds) by which messages pulled from the back-end must be acknowledged.
  • push_endpoint (str) – URL to which messages will be pushed by the back-end. If not set, the application must pull messages.
  • retain_acked_messages (bool) – (Optional) Whether to retain acked messages. If set, acked messages are retained in the subscription’s backlog for a duration indicated by message_retention_duration.
  • message_retention_duration (datetime.timedelta) – (Optional) Whether to retain acked messages. If set, acked messages are retained in the subscription’s backlog for a duration indicated by message_retention_duration. If unset, defaults to 7 days.
Return type:

Subscription

Returns:

The subscription created with the passed in arguments.

classmethod from_api_repr(resource, client)[source]#

Factory: construct a topic given its API representation

Parameters:
  • resource (dict) – topic resource representation returned from the API
  • client (google.cloud.pubsub.client.Client) – Client which holds credentials and project configuration for the topic.
Return type:

google.cloud.pubsub.topic.Topic

Returns:

Topic parsed from resource.

Raises:

ValueError if client is not None and the project from the resource does not agree with the project from the client.

project#

Project bound to the topic.

full_name#

Fully-qualified name used in topic / subscription APIs

create(client=None)[source]#

API call: create the topic via a PUT request

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/create

Example:

    topic = client.topic(TOPIC_NAME)
    topic.create()              # API request
Parameters:client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current topic.
exists(client=None)[source]#

API call: test for the existence of the topic via a GET request

See https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/get

Example:

    assert not topic.exists()   # API request
    topic.create()              # API request
    assert topic.exists()       # API request
Parameters:client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current topic.
Return type:bool
Returns:Boolean indicating existence of the topic.
delete(client=None)[source]#

API call: delete the topic via a DELETE request

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/delete

Example:

    assert topic.exists()       # API request
    topic.delete()
    assert not topic.exists()   # API request
Parameters:client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current topic.
publish(message, client=None, **attrs)[source]#

API call: publish a message to a topic via a POST request

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/publish

Example without message attributes:

    topic.publish(b'This is the message payload')               # API request

With message attributes:

    topic.publish(b'Another message payload', extra='EXTRA')    # API request
Parameters:
  • message (bytes) – the message payload
  • client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current topic.
  • attrs (dict (string -> string)) – key-value pairs to send as message attributes
Return type:

str

Returns:

message ID assigned by the server to the published message

batch(client=None, **kwargs)[source]#

Return a batch to use as a context manager.

Example:

    with topic.batch() as batch:
        batch.publish(PAYLOAD1)
        batch.publish(PAYLOAD2, extra=EXTRA)

Note

The only API request happens during the __exit__() of the topic used as a context manager, and only if the block exits without raising an exception.

Parameters:
  • client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current topic.
  • kwargs (dict) – Keyword arguments passed to the Batch constructor.
Return type:

Batch

Returns:

A batch to use as a context manager.

list_subscriptions(page_size=None, page_token=None, client=None)[source]#

List subscriptions for the project associated with this client.

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics.subscriptions/list

Example:

    for subscription in topic.list_subscriptions():   # API request(s)
        do_something_with(subscription)
Parameters:
  • page_size (int) – maximum number of topics to return, If not passed, defaults to a value set by the API.
  • page_token (str) – opaque marker for the next “page” of topics. If not passed, the API will return the first page of topics.
  • client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current topic.
Return type:

Iterator

Returns:

Iterator of Subscription accessible to the current topic.

get_iam_policy(client=None)[source]#

Fetch the IAM policy for the topic.

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/getIamPolicy

Example:

    policy = topic.get_iam_policy()             # API request
Parameters:client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current batch.
Return type:google.cloud.pubsub.iam.Policy
Returns:policy created from the resource returned by the getIamPolicy API request.
set_iam_policy(policy, client=None)[source]#

Update the IAM policy for the topic.

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/setIamPolicy

Example:

    ALL_USERS = policy.all_users()
    policy.viewers = [ALL_USERS]
    LOGS_GROUP = policy.group('cloud-logs@google.com')
    policy.editors = [LOGS_GROUP]
    new_policy = topic.set_iam_policy(policy)   # API request
Parameters:
Return type:

google.cloud.pubsub.iam.Policy

Returns:

updated policy created from the resource returned by the setIamPolicy API request.

check_iam_permissions(permissions, client=None)[source]#

Verify permissions allowed for the current user.

See: https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/testIamPermissions

Example:

    from google.cloud.pubsub.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE
    TO_CHECK = [OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE]
    ALLOWED = topic.check_iam_permissions(TO_CHECK)
    assert set(ALLOWED) == set(TO_CHECK)
Parameters:
  • permissions (list of string) – list of permissions to be tested
  • client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current batch.
Return type:

sequence of string

Returns:

subset of permissions allowed by current IAM policy.

class google.cloud.pubsub.topic.Batch(topic, client, max_interval=inf, max_messages=inf, max_size=9437184)[source]#

Bases: object

Context manager: collect messages to publish via a single API call.

Helper returned by :meth:Topic.batch

Parameters:
  • topic (google.cloud.pubsub.topic.Topic) – the topic being published
  • client (google.cloud.pubsub.client.Client) – The client to use.
  • max_interval (float) – The maximum interval, in seconds, before the batch will automatically commit. Note that this does not run a background loop; it just checks when each message is published. Therefore, this is intended for situations where messages are published at reasonably regular intervals. Defaults to infinity (off).
  • max_messages (float) – The maximum number of messages to hold in the batch before automatically commiting. Defaults to infinity (off).
  • max_size (int) – The maximum size that the serialized messages can be before automatically commiting. Defaults to 9 MB (slightly less than the API limit).
publish(message, **attrs)[source]#

Emulate publishing a message, but save it.

Parameters:
  • message (bytes) – the message payload
  • attrs (dict (string -> string)) – key-value pairs to send as message attributes
commit(client=None)[source]#

Send saved messages as a single API call.

Parameters:client (Client or NoneType) – the client to use. If not passed, falls back to the client stored on the current batch.