如何在Python中处理传入的PubSub消息?

2024-04-26 06:47:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Debian上创建了一个云计算引擎实例,并成功地创建了一个主题的推送订阅

from google.cloud import pubsub_v1

project_id = "censored"
topic_name = "censored"
subscription_name = "censored"
endpoint = "https://censored.appspot.com/pubsub/push?token=censored"

def create_push_subscription(project_id,
                             topic_name,
                             subscription_name,
                             endpoint):
    """Create a new push subscription on the given topic."""
    # [START pubsub_create_push_subscription]

    subscriber = pubsub_v1.SubscriberClient()
    topic_path = subscriber.topic_path(project_id, topic_name)
    subscription_path = subscriber.subscription_path(
        project_id, subscription_name)

    push_config = pubsub_v1.types.PushConfig(
        push_endpoint=endpoint)

    subscription = subscriber.create_subscription(
        subscription_path, topic_path, push_config)

    print('Push subscription created: {}'.format(subscription))
    print('Endpoint for subscription is: {}'.format(endpoint))
    # [END pubsub_create_push_subscription]

create_push_subscription(project_id, topic_name, subscription_name, endpoint)

但我不确定传入消息是如何到达的。我已经找到了这个示例代码来解析消息,但是我不确定如何让它在后台监视并在传入消息到达时“激活”。在

^{pr2}$

例如,此代码将返回

NameError: name 'message' is not defined

预计。。。在

有人能帮我把它安装好吗?在

我知道它在PULL中是不同的,因为消息将在PULL过程中定义,但是如果可能的话,我希望将其保持为PUSH。在


Tags: pathnameprojectidconfig消息topiccreate
1条回答
网友
1楼 · 发布于 2024-04-26 06:47:43

您需要创建一个长时间运行的进程,该进程要么能够连续轮询新消息(请求订阅),要么具有可访问的端点来接收新消息(推送订阅)。在

请看这里的示例:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/pubsub/cloud-client/subscriber.py,以及这里的push和pull的区别:https://cloud.google.com/pubsub/docs/subscriber

相关问题 更多 >