Skip to content

Instantly share code, notes, and snippets.

@ilyasahsan123
Created November 11, 2018 08:06
Show Gist options
  • Select an option

  • Save ilyasahsan123/ed6e017967c130a09e89a535df270033 to your computer and use it in GitHub Desktop.

Select an option

Save ilyasahsan123/ed6e017967c130a09e89a535df270033 to your computer and use it in GitHub Desktop.
import argparse
def list_subscriptions_in_topic(project_id, topic_name):
from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)
for subscription in publisher.list_topic_subscriptions(topic_path):
print(subscription)
def create_subscription(project_id, topic_name, subscription_name):
from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path(project_id, topic_name)
subscription_path = subscriber.subscription_path(
project_id, subscription_name)
subscription = subscriber.create_subscription(
subscription_path, topic_path)
print('Subscription created: {}'.format(subscription))
def receive_messages(project_id, subscription_name):
import time
from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(
project_id, subscription_name)
def callback(message):
print('Received message: {}'.format(message))
message.ack()
subscriber.subscribe(subscription_path, callback=callback)
print('Listening for messages on {}'.format(subscription_path))
while True:
time.sleep(60)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('project_id', help='Your Google Cloud project ID')
subparsers = parser.add_subparsers(dest='command')
list_in_topic_parser = subparsers.add_parser(
'list_in_topic', help=list_subscriptions_in_topic.__doc__)
list_in_topic_parser.add_argument('topic_name')
create_parser = subparsers.add_parser(
'create', help=create_subscription.__doc__)
create_parser.add_argument('topic_name')
create_parser.add_argument('subscription_name')
receive_parser = subparsers.add_parser(
'receive', help=receive_messages.__doc__)
receive_parser.add_argument('subscription_name')
args = parser.parse_args()
if args.command == 'list_in_topic':
list_subscriptions_in_topic(args.project_id, args.topic_name)
elif args.command == 'create':
create_subscription(
args.project_id, args.topic_name, args.subscription_name)
elif args.command == 'receive':
receive_messages(args.project_id, args.subscription_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment