Skip to content

Instantly share code, notes, and snippets.

@DSdatsme
Created January 5, 2023 09:57
Show Gist options
  • Save DSdatsme/3a21f150850c567e45534d845ad3f3e5 to your computer and use it in GitHub Desktop.
Save DSdatsme/3a21f150850c567e45534d845ad3f3e5 to your computer and use it in GitHub Desktop.
Code to pull PubSub messages one at at time
# Import the necessary libraries
from google.cloud import pubsub_v1
# Set the variables for your project, subscription, and maximum number of messages to pull
project_id = "proj-id"
subscription_name = "darshit-sub"
max_messages = 1
# Create a subscriber client
subscriber = pubsub_v1.SubscriberClient()
# Set the subscription path
subscription_path = subscriber.subscription_path(project_id, subscription_name)
while True:
# Pull the messages from the subscription
response = subscriber.pull(request={"subscription": subscription_path, "max_messages": max_messages})
# Get the list of messages
messages = response.received_messages
if not len(messages):
print("no messages in queue")
break
# Process the messages one at a time
for message in messages:
# Print the message data
print(message.message.data)
# Acknowledge the message
subscriber.acknowledge(
request={"subscription": subscription_path, "ack_ids": [message.ack_id]}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment