简体   繁体   中英

How to return a JSON from Google Cloud functions using PUBSUB as trigger?

I am publishing to topics using Python pubsub client, and there is a cloud function set up that is triggered by pubsub messages. I can trigger the function properly and generate the desired return value but I cant figure to return that value to publisher/client side. Thanks everyone!

client code:

def call_getTime():

    message_future = publisher.publish(topic_path,
                                       data=data,
                                       )
    message_future.add_done_callback(callback)
    print(message_future.result())


def callback(message_future):
    if message_future.exception(timeout=30):
        print('Publishing message threw an Exception {}.'.format(
            message_future.exception()))
    else:
        print(message_future.result())

Cloud Function:

def getTime(data, context):
        r = {'time': time.time()}
        return flask.jsonify(r)

Pubsub functions don't "return" messages. They just consume messages, and they don't normally care where the message came from. It's not a two-way form of communication.

If you want two-way communications, use an HTTP trigger instead. You can send a message back in the body of the HTTP response.

If you can't use HTTP for whatever reason and must stick with pubsub, consider publishing another message to another topic, and arrange for the sender to receive that message on that other topic. Or use some sort of webhook to notify someone that the message was handled.

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