#!/usr/bin/env python # coding: utf-8 # In[1]: from google.cloud import pubsub_v1 # In[2]: # Set the project ID and topic name project_id = "sloetjes-project1" topic_name = "sloetjes-project1" subscription_name = "sloetjes-final-project1" # In[3]: # Create a publisher client publisher = pubsub_v1.PublisherClient() # In[4]: # Create the fully qualified topic path topic_path = publisher.topic_path(project_id, topic_name) # In[5]: # Create the Pub/Sub topic topic = publisher.create_topic(name = topic_path) # In[ ]: # Print the topic name print(f"Topic created: {topic.name}") # In[ ]: # Create the subscription if it doesn't exist subscription_path = subscriber.subscription_path(project_id, subscription_name) topic_path = publisher.topic_path(project_id, topic_name) # Publish a message to the topic message = "Hello, World!" data = message.encode("utf-8") publisher.publish(topic_path, data=data) print(f"Message published: {message}") # Pull the message from the subscription response = subscriber.pull(subscription_path, max_messages=1) for received_message in response.received_messages: print(f"Received message: {received_message.message.data}") # Acknowledge the message subscriber.acknowledge(subscription_path, [received_message.ack_id])