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

≡放荡痞女 提交于 2021-02-05 05:24:25

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/55082366/how-to-return-with-a-specific-status-in-a-python-google-cloud-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!