简体   繁体   中英

How to return with a specific status in a Python Google Cloud Function

I notice that I can raise or return, producing 500 or 200 responses. for example:

def random(request):
    coin = [true, false]
    if random.choice(coin):
        succeed()
    else:
        fail()

def succeed():
    return '{ "status": "success!"}'

def fail():
    raise Exception("failure")

something roughly like that will produce either a 500 or a 200 response. But it doesn't, for example, let me raise a 422 error with a body.

Can I do that?

Under the hood, Cloud Functions is just using Flask , so you can return anything that you can return from a Flask endpoint.

You can just return a body and a status code together like this:

def random(request):
    ...
    return "Can't process this entity", 422

Or, you can return a full-fledged Flask Response object :

import flask

def random(request):
    ...
    return flask.Response(status=422)

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