I am writing a REST API GET endpoint that needs to both return a response and store records to either GCP Cloud SQL (MySQL), but I want the return to not be dependent on completion of the writing of the records. Basically, my code will look like:
def predict():
req = request.json.get("instances")
resp = make_response(req)
write_to_bq(req)
write_to_bq(resp)
return resp
Is there any easy way to do this with Cloud SQL Client Library or something?
CodePudding user response:
Turns our flask has a functionality that does what I require:
@app.route("predict", method=["GET"]):
def predict():
# do some stuff with the request.json object
return jsonify(response)
@app.after_request
def after_request_func(response):
# do anything you want that relies on context of predict()
@response.call_on_close
def persist():
# this will happen after response is sent,
# so even if this function fails, the predict()
# will still get it's response out
write_to_db()
return response
One important thing is that a method tagged with after_request
must take an argument and return something of type flask.Response
. Also I think if method has call_on_close
tag, you cannot access from context of main method, so you need to define anything you want to use from the main method inside the after_request
tagged method but outside (above) the call_on_close
method.