Files
python-bootcamp/fp1.py
T

54 lines
1.9 KiB
Python
Raw Normal View History

2023-04-26 19:14:54 -04:00
from google.cloud import pubsub_v1
from google.oauth2 import service_account
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "C:/Users/Karen/AppData/Roaming/gcloud/application_default_credentials.json"
project_id = "fp-20230425"
'''
topic_name = "fp-topic-Karen"
subscription_name = "fp-subscription-Karen"
subscriber = pubsub_v1.SubscriberClient()
subscription_path = f"projects/{project_id}/subscriptions/{subscription_name}"
subscriber.delete_subscription(request={"subscription": subscription_path})
print("Subscription deleted: {}".format(subscription_path))
# Delete the topic
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)
publisher.delete_topic(request={"topic": topic_path})
print(f"Topic '{topic_name}' deleted.")
subscription_name = "fp-subscription-Karen"
subscription_path = f"projects/{project_id}/subscriptions/{subscription_name}"
'''
# Create a pubsub topic
publisher = pubsub_v1.PublisherClient()
topic_name = "fp-topic-Karen"
topic_path = publisher.topic_path(project_id, topic_name)
topic = publisher.create_topic(request={"name": topic_path})
# Create a Pub/Sub subscription
subscriber = pubsub_v1.SubscriberClient()
subscription_name = "fp-subscription-Karen"
subscription_path = subscriber.subscription_path(project_id, subscription_name)
subscription = subscriber.create_subscription(
name=subscription_path, topic=topic_path
)
# Publish a message to the topic
message = b"Hello!"
publisher.publish(topic_path, data=message)
print("Message published.")
# Pull the message from the subscription
response = subscriber.pull(subscription=subscription_path, max_messages=1)
for received_message in response.received_messages:
print("Received message: {}".format(received_message.message.data))
# Acknowledge the message to mark it as processed
subscriber.acknowledge(subscription_path, [received_message.ack_id])