简体   繁体   中英

Google Cloud PubSub - How to send multiple arguments to the Cloud Function

I have been using Google Cloud PubSub to trigger Google Cloud Functions. Until this point I have been using a single argument "uuid", now I need to send also development/production flag.

Here below is the publisher in Google App Engine/Django:

    publisher = pubsub_v1.PublisherClient()
    topic_name = 'projects/project/topics/cloudfunction_topic'
    message_to_publish = video.uuid
    publisher.publish(topic_name, data=message_to_publish.encode('utf-8'), spam='')

Here below is the subscriber section in GCF:

    if os.getenv('GCF', None):
        uuid = base64.b64decode(event['data']).decode('utf-8')

How should I change this so there can be multiple arguments (video.uuid, production/development) in the message?

Easiest way (IMO) is to create a json structure, and serialize it into a utf-8 string on the sending side, and de-serialize it back into a json structure in the GCF.

The Pub/Sub message is base64 encoded, so you can write json and send it from Pub/Sub to the Cloud Function, OR you can pass Attributes from Pub/Bub and that is both json and plain text.

For example, if you run Pub/Sub manually like this:

在此处输入图像描述

You can add Attributes:

在此处输入图像描述

The word "test" is base64 but a console.dir(event) like this for example...

    exports.getData = (event, context) => {...
      console.dir(event);

...will show this in Cloud Logging:

在此处输入图像描述

It is then fairly easy to parse and use the Pub/Sub attributes in your Cloud Function. Obviously, this is Node, but it would be similar in Python.

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