Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 326
roberto tomás Avatar asked Mar 09 '19 21:03

roberto tomás


People also ask

Is cloud function stateless?

Google Cloud Functions is a stateless execution environment, which means that the functions follow a shared-nothing architecture. Each running function is responsible for one and only one request at a time.

What is cold start in Cloud Functions?

Functions are stateless, and the execution environment is often initialized from scratch, which is called a cold start. Cold starts can take significant amounts of time to complete.

What is cloud function timeout?

Function execution time is limited by the timeout duration, which you can specify when you deploy a function. By default, a function times out after one minute (60 seconds), but you can extend this period: In Cloud Functions (1st gen), the maximum timeout duration is nine minutes (540 seconds).


1 Answers

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)
like image 148
Dustin Ingram Avatar answered Oct 06 '22 04:10

Dustin Ingram