def subscription(client: AdminClient,
                 topic: Topic) -> Generator[Subscription, None, None]:
    location = CloudZone(CloudRegion(CLOUD_REGION), ZONE_ID)
    subscription_path = SubscriptionPath(PROJECT_NUMBER, location,
                                         SUBSCRIPTION_ID)

    subscription = Subscription(
        name=str(subscription_path),
        topic=topic.name,
        delivery_config=Subscription.DeliveryConfig(
            delivery_requirement=Subscription.DeliveryConfig.
            DeliveryRequirement.DELIVER_IMMEDIATELY, ),
    )

    try:
        response = client.get_subscription(subscription.name)
    except NotFound:
        # This subscription will start receiving the first message in the topic.
        response = client.create_subscription(subscription,
                                              BacklogLocation.BEGINNING)

    yield response

    try:
        client.delete_subscription(response.name)
    except NotFound as e:
        print(e.message)
Example #2
0
def create_lite_subscription(project_number, cloud_region, zone_id, topic_id,
                             subscription_id):
    # [START pubsublite_create_subscription]
    from google.api_core.exceptions import AlreadyExists
    from google.cloud.pubsublite import AdminClient, Subscription
    from google.cloud.pubsublite.types import (
        CloudRegion,
        CloudZone,
        SubscriptionPath,
        TopicPath,
    )

    # TODO(developer):
    # project_number = 1122334455
    # cloud_region = "us-central1"
    # zone_id = "a"
    # topic_id = "your-topic-id"
    # subscription_id = "your-subscription-id"

    cloud_region = CloudRegion(cloud_region)
    location = CloudZone(cloud_region, zone_id)
    topic_path = TopicPath(project_number, location, topic_id)
    subscription_path = SubscriptionPath(project_number, location,
                                         subscription_id)
    subscription = Subscription(
        name=str(subscription_path),
        topic=str(topic_path),
        delivery_config=Subscription.DeliveryConfig(
            # Possible values for delivery_requirement:
            # - `DELIVER_IMMEDIATELY`
            # - `DELIVER_AFTER_STORED`
            # You may choose whether to wait for a published message to be successfully written
            # to storage before the server delivers it to subscribers. `DELIVER_IMMEDIATELY` is
            # suitable for applications that need higher throughput.
            delivery_requirement=Subscription.DeliveryConfig.
            DeliveryRequirement.DELIVER_IMMEDIATELY, ),
    )

    client = AdminClient(cloud_region)
    try:
        response = client.create_subscription(subscription)
        print(f"{response.name} created successfully.")
    except AlreadyExists:
        print(f"{subscription_path} already exists.")