我正在撰寫一個 REST API GET 端點,它需要回傳回應并將記錄存盤到 GCP Cloud SQL (MySQL),但我希望回傳不依賴于記錄寫入的完成。基本上,我的代碼將如下所示:
def predict():
req = request.json.get("instances")
resp = make_response(req)
write_to_bq(req)
write_to_bq(resp)
return resp
有沒有什么簡單的方法可以使用 Cloud SQL 客戶端庫或其他東西來做到這一點?
uj5u.com熱心網友回復:
Turns 我們的燒瓶具有滿足我要求的功能:
@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
一件重要的事情是帶有 標記的方法after_request必須接受一個引數并回傳一些型別的東西flask.Response。另外我認為如果方法有call_on_close標簽,你不能從主方法的背景關系中訪問,所以你需要從主方法中定義你想使用的任何東西,after_request但在方法之外(上面)call_on_close。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456696.html
上一篇:如果陳述句不適用于全域變數
