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
相关产品推荐
相关产品推荐

