Publish and acknowledge a message
Send, receive, and acknowledge an event; Pub/Sub lets producers and consumers work independently.
A repeatable topic, subscription, publish, and pull example.
SDK dependencies
Run in a new example directory
python3 -m venv .venv
source .venv/bin/activate
python -m pip install google-cloud-pubsub Save as hello.py
import os
from uuid import uuid4
from google.cloud import pubsub_v1
assert os.environ['PUBSUB_EMULATOR_HOST']
project = os.environ['GOOGLE_CLOUD_PROJECT']
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
name = 'hello-' + uuid4().hex[:12]
topic = publisher.topic_path(project, name)
subscription = subscriber.subscription_path(project, name)
publisher.create_topic(request={'name': topic}, timeout=30)
try:
subscriber.create_subscription(request={'name': subscription, 'topic': topic}, timeout=30)
try:
publisher.publish(topic, b'Hello, Pub/Sub!').result(timeout=30)
response = subscriber.pull(request={'subscription': subscription, 'max_messages': 1}, timeout=30)
assert response.received_messages
for received in response.received_messages:
print(received.message.data.decode())
subscriber.acknowledge(request={'subscription': subscription, 'ack_ids': [received.ack_id]}, timeout=30)
finally:
subscriber.delete_subscription(request={'subscription': subscription}, timeout=30)
finally:
publisher.delete_topic(request={'topic': topic}, timeout=30)
subscriber.close()
publisher.transport.close() Run the example
python hello.py Verify the result
The command completes successfully and prints the expected output shown below.
Expected output
Hello, Pub/Sub!