Skip to content

Commit

Permalink
Add the Pub/Sub handle_publisher_error sample [(#1440)](GoogleCloudPl…
Browse files Browse the repository at this point in the history
…atform/python-docs-samples#1440)

* Add the Pub/Sub handle_publisher_error sample

* Update requirements.txt

* Update publisher.py

* Update publisher.py

* Added region tag
  • Loading branch information
chenyumic authored and plamut committed Jul 10, 2020
1 parent fc54932 commit 319a1c7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
33 changes: 33 additions & 0 deletions samples/snippets/publisher.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"""

import argparse
import concurrent.futures

from google.cloud import pubsub_v1

Expand Down Expand Up @@ -123,6 +124,38 @@ def publish_messages_with_futures(project, topic_name):
# [END pubsub_publisher_concurrency_control]


def publish_messages_with_error_handler(project, topic_name):
"""Publishes multiple messages to a Pub/Sub topic with an error handler."""
# [START pubsub_publish_messages_error_handler]
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project, topic_name)

# When you publish a message, the client returns a Future. This Future
# can be used to track if an error has occurred.
futures = []

def callback(f):
exc = f.exception()
if exc:
print('Publishing message on {} threw an Exception {}.'.format(
topic_name, exc))

for n in range(1, 10):
data = u'Message number {}'.format(n)
# Data must be a bytestring
data = data.encode('utf-8')
message_future = publisher.publish(topic_path, data=data)
message_future.add_done_callback(callback)
futures.append(message_future)

# We must keep the main thread from exiting to allow it to process
# messages in the background.
concurrent.futures.wait(futures)

print('Published messages.')
# [END pubsub_publish_messages_error_handler]


def publish_messages_with_batch_settings(project, topic_name):
"""Publishes multiple messages to a Pub/Sub topic with batch settings."""
# [START pubsub_publisher_batch_settings]
Expand Down
3 changes: 2 additions & 1 deletion samples/snippets/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
google-cloud-pubsub==0.33.0
google-cloud-pubsub==0.32.1
futures==3.1.1; python_version < '3'

0 comments on commit 319a1c7

Please sign in to comment.