Search code examples
google-cloud-platformgoogle-cloud-functionsgoogle-cloud-tasks

Cloud Task expects payload of type 'Bytes', how do I send a dictionary?


I'm trying to learn how to queue up tasks that get processed by a cloud function. Following the example code provided https://cloud.google.com/tasks/docs/creating-http-target-tasks

I am also using the example cloud function code for Python. The cloud function is expecting some args or JSON like below:

{"message": "hello Ari"}

However when I try and set the payload for the task to a dictionary it says it can't encode a dict, so how do I send something other than a string. I'm essentially wanting to send keys and values for the cloud function to interpret:

{
"file": "image.png",
"user": "ari",
"process": "resize",
}

So I guess my question is, how do I send information with context and how do I interpret the payload on the cloud function side

Basically a user uploads an image, image gets stored in GCS, a task gets created to resize the image (or do something), the cloud function is triggered by the task queue, it reads in the bucket information and who the user is, does the job, updates the file meta data in firestore to indicate to the user the job is complete.


Solution

  • It was so simple. In the route/function that creates the task (see link above for code sample), change the payload variable to look like this.

    payload = json.dumps({
        "message": "hello",
        "user": "ari"
    })
    

    Then in your cloud function or endpoint use this to transfer it back into a dictionary:

    payload = request.get_data(as_text=True)
    args = json.loads(payload)
    
    message = args.get("message")