@@ -12,8 +12,9 @@ Instantiating a subscriber client is straightforward:
1212.. code-block :: python
1313
1414 from google.cloud import pubsub
15- subscriber = pubsub.SubscriberClient()
1615
16+ with pubsub.SubscriberClient() as subscriber:
17+ # ...
1718
1819 Creating a Subscription
1920-----------------------
@@ -41,8 +42,10 @@ to subscribe to, and it must already exist. Once you have that, it is easy:
4142 # publisher = pubsub.PublisherClient()
4243
4344 topic_path = publisher.topic_path(PROJECT , TOPIC )
44- sub_path = subscriber.subscription_path(PROJECT , SUBSCRIPTION )
45- subscriber.create_subscription(request = {" name" : sub_path, " topic" : topic_path})
45+
46+ with pubsub.SubscriberClient() as subscriber:
47+ sub_path = subscriber.subscription_path(PROJECT , SUBSCRIPTION )
48+ subscriber.create_subscription(request = {" name" : sub_path, " topic" : topic_path})
4649
4750 Once you have created a subscription (or if you already had one), the next
4851step is to pull data from it.
@@ -56,6 +59,8 @@ To pull the messages synchronously, use the client's
5659
5760.. code-block :: python
5861
62+ # Wrap the following code in `with pubsub.SubscriberClient() as subscriber:`
63+
5964 # Substitute PROJECT and SUBSCRIPTION with appropriate values for your
6065 # application.
6166 subscription_path = subscriber.subscription_path(PROJECT , SUBSCRIPTION )
@@ -88,6 +93,8 @@ be dropped by this client and the backend will try to re-deliver them.
8893
8994.. code-block :: python
9095
96+ # Wrap the following code in `with pubsub.SubscriberClient() as subscriber:`
97+
9198 ack_ids = [] # TODO : populate with `ack_ids` of the messages to NACK
9299 ack_deadline_seconds = 0
93100 subscriber.modify_ack_deadline(
@@ -109,6 +116,8 @@ each message received.
109116
110117.. code-block :: python
111118
119+ # Wrap the following code in `with pubsub.SubscriberClient() as subscriber:`
120+
112121 # Substitute PROJECT and SUBSCRIPTION with appropriate values for your
113122 # application.
114123 subscription_path = subscriber.subscription_path(PROJECT , SUBSCRIPTION )
@@ -147,6 +156,8 @@ Here is an example:
147156 do_something_with(message) # Replace this with your actual logic.
148157 message.ack() # Asynchronously acknowledge the message.
149158
159+ # Wrap the following code in `with pubsub.SubscriberClient() as subscriber:`
160+
150161 # Substitute PROJECT and SUBSCRIPTION with appropriate values for your
151162 # application.
152163 subscription_path = subscriber.subscription_path(PROJECT , SUBSCRIPTION )
@@ -177,7 +188,8 @@ thread will be set on the future.
177188 try :
178189 future.result()
179190 except Exception as ex:
180- subscription.close()
191+ # Close the subscriber if not using a context manager.
192+ subscriber.close()
181193 raise
182194
183195 Finally, you can use
0 commit comments