我写了一个简单的代码来打印来自pubsub触发器云函数的数据和上下文。
def-main(事件,上下文(:"quot"Pub/Sub将触发的后台云功能。Args:event(dict(:具有特定于此类型的数据的字典事件data
字段包含PubsubMessage消息。这个attributes
字段将包含自定义属性(如果有的话(。context(google.cloud.functions.context(:cloud functions事件元数据。event_id
字段包含发布/子消息IDtimestamp
字段包含发布时间。"quot"导入base64
print("""This Function was triggered by messageId {} published at {}
""".format(context.event_id, context.timestamp))
if 'data' in event:
name = base64.b64decode(event['data']).decode('utf-8')
else:
name = 'World'
print('Hello {}!'.format(name))
云函数部署成功,但每当我在日志中向触发器主题发布消息时,我都看不到任何函数执行语句。
我已经验证了我只调用main函数,并发布到正确的pubsub主题。
我看不到任何错误语句,因此无法调试。
任何建议都将有助于
我在python 3.8
运行时测试了您的代码函数,一切都很好,您是否使用相同的pub/sub主题来推送新消息?
这是我在电脑上用来发送pubsub消息的代码。
from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
# The `topic_path` method creates a fully qualified identifier
# in the form `projects/{project_id}/topics/{topic_id}`
topic_path = publisher.topic_path("myprojectID", "test")
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.")
requirements.txt
google-cloud-pubsub
这是全功能代码
import base64
def hello_pubsub(event, context):
print("""This Function was triggered by messageId {} published at {}
""".format(context.event_id, context.timestamp))
if 'data' in event:
name = base64.b64decode(event['data']).decode('utf-8')
else:
name = 'World'
print('Hello {}!'.format(name))
预期输出
This Function was triggered by messageId 1449686821351887 published at 2020-08-20T21:26:30.600Z
日志可能会在stackdriver 上延迟10-30秒出现