Skip to content

Instantly share code, notes, and snippets.

@aliafshar
Created July 16, 2014 19:21
Show Gist options
  • Select an option

  • Save aliafshar/fa353ab06c88b19dca8b to your computer and use it in GitHub Desktop.

Select an option

Save aliafshar/fa353ab06c88b19dca8b to your computer and use it in GitHub Desktop.
# Create a connection
pubsub = Connection(PROJECT, credentials)
# Quick intro
# 1. publisher
topic = pubsub.create_topic('my-topic')
for i in range(100):
topic.publish('msg-{}'.format(i))
# 2. subscriber
sub = pubsub.subscribe('my-topic', 'my-sub')
for msg in sub:
print msg
# Create a topic.
my_topic = pubsub.create_topic('banana')
# This is what resource (topic and subscription names) look like.
print my_topic.name
# The simple (short) name > banana
print my_topic.fully_qualified_name
# The fullly qualified name > /topics/<PROJECT>/banana
# List all the topics.
for topic in pubsub.list_topics():
print topic
# Or even just iterate the connection itself.
for topic in pubsub:
print topic
# Subscribe to a topic.
my_sub = pubsub.subscribe('banana', 'my-subscription')
# As usual you can pass a topic or a fully qualified name.
my_sub = pubsub.subscribe(my_topic, 'my-subscription')
# Or on the topic itself
my_topic.subscribe('my-subscription')
# Publish to a topic.
pubsub.publish('banana', 'test-message')
# As usual you can pass a topic or a fully qualified name.
pubsub.publish(my_topic, 'test-message')
# Or even if you like, use a more object-style, seems nicer somehow
my_topic.publish('test-messages')
# Pull a notification.
message = pubsub.pull('my-subscription')
print message
# Or if you like objects
my_sub.pull()
# Poll for notifications and call a callback.
def on_message(msg):
print msg, 'received'
my_sub.add_callback(on_message)
# Or just block until you get notified.
msg = my_sub.wait()
# Ack a notification.
pubsub.ack(message)
# Or again, using objects
message.ack()
# Get a topic.
fetched_topic = pubsub.get_topic('banana')
# also accepts a topic or a fully qualified name
fetched_topic = pubsub.get_topic(my_topic)
fetched_topic = pubsub.get_topic('/topics/' + PROJECT + 'banana')
# Delete a topic.
pubsub.delete_topic('banana')
pubsub.delete_topic(my_topic)
# Or
my_topic.delete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment