如何在Python Google Cloud Function中以特定状态返回 [英] How to return with a specific status in a Python Google Cloud Function

查看:49
本文介绍了如何在Python Google Cloud Function中以特定状态返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到自己可以举起或返回,产生500或200个回复.例如:

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")

大致类似的结果将产生500或200的响应.但是,例如,它不会让我在身体上引发422错误.

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.

我可以这样做吗?

推荐答案

在后台,Cloud Functions仅使用 Flask ,因此您可以返回可以从Flask端点返回的任何内容.

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

或者,您可以返回完整的Flask Response 对象:

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

import flask

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

这篇关于如何在Python Google Cloud Function中以特定状态返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆