Exemplo n.º 1
0
def start_subscriber(loop, topic):
    client = SubscriberClient()

    project_id = os.getenv('GCP_PROJECT')
    topic_path = PublisherClient.topic_path(project_id, topic)
    subscription_path = PublisherClient.subscription_path(project_id, topic)

    # Create subscription if it doesn't already exist
    try:
        client.create_subscription(subscription_path, topic_path)
    except google.api_core.exceptions.PermissionDenied as e:
        raise TypeError('Please set the GCP_PROJECT environment variable') from e

    # Subscribe to the subscription, receiving a Future that acts as a keepalive
    keep_alive = client.subscribe(subscription_path, message_callback)

    # Have the client run forever, pulling messages from this subscription,
    # passing them to the specified callback function, and wrapping it in an
    # asyncio task.
    client.run_forever(keep_alive)
Exemplo n.º 2
0
async def start_subscriber(topic):
    client = SubscriberClient()
    project_id = os.getenv("GCP_PROJECT")
    topic_path = PublisherClient.topic_path(project_id, topic)
    subscription_path = PublisherClient.subscription_path(project_id, topic)

    # Create subscription if it doesn't already exist
    try:
        await client.create_subscription(subscription_path, topic_path)
    except aiohttp.client_exceptions.ClientResponseError as e:
        if e.status == 409:  # Subscription exists
            pass
        else:
            raise TypeError("Please set the GCP_PROJECT environment variable") from e

    # For demo with Pub/Sub emulator, maybe ack_deadline_cache_timeout 300
    # On GCP, default seems fine.
    # For more options, check gcloud-aio docs:
    # https://github.com/talkiq/gcloud-aio/tree/master/pubsub
    await subscribe(subscription_path, message_callback, client, ack_deadline_cache_timeout=300)