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

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

问题描述

我注意到我可以提出或返回,产生 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 函数中返回特定状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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