如何使用 运行 Python 脚本将数据发送到 Google PubSub

How to run Python script to send data to Google PubSub

从 Google 控制台,我正在创建一个主题并发布它,它工作正常。现在我想通过 Python 脚本来完成,我已经完成了,但我不知道将这些文件放在 Google Pub/Sub 中的什么位置。

有人可以教我如何使用脚本完成吗?我是新来的,我是学生。我没用过GooglePub/Sub。我只想制作一些随机数据并将其发送到 Pub/Sub 这就是我想要的。

有人告诉我 运行 那些脚本需要网络托管,是真的吗?请简要指导我。三天来我一直在阅读文档,现在我脑子里的一切都搞砸了。提前谢谢。

您唯一需要遵循的文档是 Pub/Sub quickstart。 "web hosting" 你需要的是一个 GCP 项目,没有别的。

您可以从 GCP Cloud Shell 本身执行此快速入门,使用 nanovim 创建文件。请记住在脚本中设置 project_idtopic_namesubscription_name

正如 Guillermo Cacheda 所说的那样,您所需要的只是 PUB/SUB 快速入门。

但是,首先您需要一个部署在 GCP(Google 云平台)上的项目。 假设您有一个项目并且知道 project_ID。 您需要使用 pip 安装 google-cloud-pubsub。

/确保您按照 python 开发设置指南/

中的描述使用 virtualenv
pip install --upgrade google-cloud-pubsub

/创建一个您可以发布或订阅的主题。/

gcloud pubsub topics create my-topic

/发布消息/

from google.cloud import pubsub_v1

/TODO project_id = "Your Google Cloud Project ID" TODO topic_name = "Your Pub/Sub topic name"/

publisher = pubsub_v1.PublisherClient()

/topic_path方法创建完全限定标识符 形式为 projects/{project_id}/topics/{topic_name}/

topic_path = publisher.topic_path(project_id, topic_name)

for n in range(1, 10):
    data = u"Message number {}".format(n)
    # Data must be a bytestring
    data = data.encode("utf-8")
    # When you publish a message, the client returns a future.
    future = publisher.publish(topic_path, data=data)
    print(future.result())

print("Published messages.")

/接收消息/

from google.cloud import pubsub_v1

/TODO project_id = "Your Google Cloud Project ID" , TODO subscription_name = "Your Pub/Sub subscription name", TODO 超时 = 5.0 # "How long the subscriber should listen for messages in seconds"/

subscriber = pubsub_v1.SubscriberClient()

/subscription_path方法创建完全限定标识符 以 projects/{project_id}/subscriptions/{subscription_name}/

的形式
subscription_path = subscriber.subscription_path(
    project_id, subscription_name
)

def callback(message):
    print("Received message: {}".format(message))
    message.ack()

streaming_pull_future = subscriber.subscribe(
    subscription_path, callback=callback
)
print("Listening for messages on {}..\n".format(subscription_path))
如果未设置 timeout

/result() 将无限期阻塞, 除非先遇到异常/ 尝试: streaming_pull_future.result(超时=超时) 除了: streaming_pull_future.cancel()

/最后为了避免您的 GCP 帐户对资源产生费用,请使用以下命令删除主题和订阅/

gcloud pubsub subscriptions delete my-sub
gcloud pubsub topics delete my-topic

/请注意以上代码来自 python 的 GCP 文档 Quickstart-client-libraries。/