You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现GCP Cloud Function获取PubSub消息属性

获取PubSub消息中的属性值

你当前的代码只处理了PubSub消息的data内容,而消息的属性存储在触发事件的attributes字段里,这是一个字典结构,直接通过键名就能读取对应的属性值。

修改后的代码如下:

import base64

def hello_pubsub(event, context):
    # 获取并解码消息内容
    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    print(f"消息内容: {pubsub_message}")
    
    # 获取消息属性
    attributes = event.get('attributes', {})
    origin = attributes.get('origin')
    username = attributes.get('username')
    
    # 打印属性值
    if origin:
        print(f"origin属性值: {origin}")
    if username:
        print(f"username属性值: {username}")

代码说明:

  • 使用event.get('attributes', {})获取属性字典,避免消息无属性时抛出KeyError
  • 通过attributes.get('属性名')读取具体属性值,属性不存在时返回None,不会触发异常
  • 若确定属性必然存在,也可以直接用event['attributes']['origin']读取,但这种方式容错性较差

用你提供的gcloud命令发布消息后,Cloud Function的日志会输出:

消息内容: test
origin属性值: gcloud-sample
username属性值: gcp

内容的提问来源于stack exchange,提问作者Ashok KS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:05:37