Search code examples
pythongoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-pubsub

Cloud Function to retrieve attributes from PubSub - Python


I created a GCP Cloud Functions which is triggered by a PubSub topic.

import base64

def hello_pubsub(event, context):
    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    print(pubsub_message)

I publish messages using the below command which triggers the Cloud Functions.

gcloud pubsub topics publish test-topic --message="test" \
  --attribute="origin=gcloud-sample,username=gcp"

Using this I can access only the "message" part of the topic. How can I access the "attribute" values from the PubSub message. I want to fetch the origin and username from the topic.


Solution

  • From the documentation for v1 Cloud Functions:

    """
    event (dict):  The dictionary with data specific to this type of
                    event. The `@type` field maps to
                     `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                    The `data` field maps to the PubsubMessage data
                    in a base64-encoded string. The `attributes` field maps
                    to the PubsubMessage attributes if any is present.
    """
    

    So I think just using event['attributes'] should work. See also.