如何启动并运行python pubsub教程?

时间:2019-08-27 01:34:19

标签: python google-cloud-platform google-cloud-pubsub

我正在研究此内容,该内容应该是GCP网站上简单/直观的tutorial,才能开始在PubSub上使用。我正在使用10.14.5,使用本教程建议的python环境。以下是pub.py的代码。 (和的代码sub.py与本教程中的代码相同。)

pub.py

#!/usr/bin/env python

# [START pubsub_quickstart_pub_all]
import argparse,os
import time
# [START pubsub_quickstart_pub_deps]
from google.cloud import pubsub_v1
# [END pubsub_quickstart_pub_deps]


def get_callback(api_future, data):
    """Wrap message data in the context of the callback function."""

    def callback(api_future):
        try:
            print("Published message {} now has message ID {}".format(
                data, api_future.result()))
        except Exception:
            print("A problem occurred when publishing {}: {}\n".format(
                data, api_future.exception()))
            raise
    return callback


def pub(project_id, topic_name):
    """Publishes a message to a Pub/Sub topic."""
    # [START pubsub_quickstart_pub_client]
    # Initialize a Publisher client
    client = pubsub_v1.PublisherClient()
    # [END pubsub_quickstart_pub_client]
    # Create a fully qualified identifier in the form of
    # `projects/{project_id}/topics/{topic_name}`
    topic_path = client.topic_path(project_id, topic_name)

    # Data sent to Cloud Pub/Sub must be a bytestring
    data = b"Hello, World!"

    # When you publish a message, the client returns a future.
    api_future = client.publish(topic_path, data=data)
    api_future.add_done_callback(get_callback(api_future, data))

    print("topic path:" + topic_path)
    print("GOOGLE_APPLICATION_CREDENTIALS:" + os.environ['GOOGLE_APPLICATION_CREDENTIALS'])
    # Keep the main thread from exiting until background message
    # is processed.
    while api_future.running():
        time.sleep(0.1)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument('project_id', help='Google Cloud project ID')
    parser.add_argument('topic_name', help='Pub/Sub topic name')

    args = parser.parse_args()

    pub(args.project_id, args.topic_name)
# [END pubsub_quickstart_pub_all]

但是,当我运行此代码时:

python pub.py $PROJECT hello_topic

脚本,我没有得到预期的行为。我期望这个命令说一条消息已经发布,而订户命令(由另一终端上的python sub.py $PROJECT sub_one调用)应该说已经收到一条消息。

此外,当我运行pub.py并在此处检查控制台时:

https://console.cloud.google.com/cloudpubsub/topic/detail/hello_topic?project=MYPROJECT

Publish Message Count指示客户端似乎未发布任何消息。

我很确定设置可以,因为:

$ gcloud pubsub topics list
name: projects/<MYPROJECT>/topics/hello_topic

$ gcloud pubsub topics list-subscriptions hello_topic
---
  projects/<MYPROJECT>/subscriptions/sub_two
---
  projects/<MYPROJECT>/subscriptions/sub_one

此外,使用gcloud实用程序直接发送消息,也会产生预期的结果。

$ gcloud pubsub topics publish hello_topic --message "test message 123"
messageIds:
- '709682720030464'

$ gcloud pubsub subscriptions pull --auto-ack one_sub
┌──────────────────┬─────────────────┬────────────┐
│       DATA       │    MESSAGE_ID   │ ATTRIBUTES │
├──────────────────┼─────────────────┼────────────┤
│ test message 123 │ 709682720030464 │            │
└──────────────────┴─────────────────┴────────────┘

我也相信凭据已正确设置,尽管我不确定如何进行验证。

有人可以提供一些指示,让我进一步检查/验证以获得期望的行为吗?

0 个答案:

没有答案