Skip to content

Commit f67eaa4

Browse files
Pub/Sub: improve pub.py (#2403)
* print number of messages published * two nit's
1 parent d884b61 commit f67eaa4

File tree

1 file changed

+12
-8
lines changed
  • pubsub/cloud-client/quickstart

1 file changed

+12
-8
lines changed

pubsub/cloud-client/quickstart/pub.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@
2222
# [END pubsub_quickstart_pub_deps]
2323

2424

25-
def get_callback(api_future, data):
25+
def get_callback(api_future, data, ref):
2626
"""Wrap message data in the context of the callback function."""
27-
2827
def callback(api_future):
2928
try:
3029
print("Published message {} now has message ID {}".format(
3130
data, api_future.result()))
31+
ref["num_messages"] += 1
3232
except Exception:
3333
print("A problem occurred when publishing {}: {}\n".format(
3434
data, api_future.exception()))
@@ -39,24 +39,28 @@ def callback(api_future):
3939
def pub(project_id, topic_name):
4040
"""Publishes a message to a Pub/Sub topic."""
4141
# [START pubsub_quickstart_pub_client]
42-
# Initialize a Publisher client
42+
# Initialize a Publisher client.
4343
client = pubsub_v1.PublisherClient()
4444
# [END pubsub_quickstart_pub_client]
4545
# Create a fully qualified identifier in the form of
4646
# `projects/{project_id}/topics/{topic_name}`
4747
topic_path = client.topic_path(project_id, topic_name)
4848

49-
# Data sent to Cloud Pub/Sub must be a bytestring
49+
# Data sent to Cloud Pub/Sub must be a bytestring.
5050
data = b"Hello, World!"
5151

52+
# Keep track of the number of published messages.
53+
ref = dict({"num_messages": 0})
54+
5255
# When you publish a message, the client returns a future.
5356
api_future = client.publish(topic_path, data=data)
54-
api_future.add_done_callback(get_callback(api_future, data))
57+
api_future.add_done_callback(get_callback(api_future, data, ref))
5558

56-
# Keep the main thread from exiting until background message
57-
# is processed.
59+
# Keep the main thread from exiting while the message future
60+
# gets resolved in the background.
5861
while api_future.running():
59-
time.sleep(0.1)
62+
time.sleep(0.5)
63+
print("Published {} message(s).".format(ref["num_messages"]))
6064

6165

6266
if __name__ == '__main__':

0 commit comments

Comments
 (0)