简体   繁体   中英

Cloud Function with pubsub trigger topic is not working

I have wrote a simple code to print data and context from a pubsub trigger cloud function.

def main(event, context): """Background Cloud Function to be triggered by Pub/Sub. Args: event (dict): The dictionary with data specific to this type of event. The data field contains the PubsubMessage message. The attributes field will contain custom attributes if there are any. context (google.cloud.functions.Context): The Cloud Functions event metadata. The event_id field contains the Pub/Sub message ID. The timestamp field contains the publish time. """ import 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))

Cloud function is deployed successfully but whenever I publish a message to the trigger topic in logs I cannot see any function execution statement.

I have already verified that I am calling main function only and publishing to a right pubsub topic.

I cannot see any error statement so I am not able to debug.

Any Suggestion will be helpful

I tested your code function in python 3.8 runtime and all works fine, are you using the same pub/sub topic for push new messages?

This the code that I used on my computer to send pubsub messages.

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

This is full function code

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))

Expected output

This Function was triggered by messageId 1449686821351887 published at 2020-08-20T21:26:30.600Z

The logs may appears with a delay of 10-30 secs on stackdriver

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM