From 7d41f00cce8648d2b2b308596f96c6ba50507c38 Mon Sep 17 00:00:00 2001 From: Tomasz Torcz Date: Sun, 21 Jul 2024 16:54:33 +0200 Subject: [PATCH] api: only open database connection while handling requests Helps with recovery when database restarts during long-held connections. Code from https://docs.peewee-orm.com/en/3.15.3/peewee/database.html#flask --- src/api.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/api.py b/src/api.py index 1f63f8c..88c18f7 100644 --- a/src/api.py +++ b/src/api.py @@ -20,6 +20,19 @@ else: app = Flask(__name__) +# This hook ensures that a connection is opened to handle any queries +# generated by the request. +@app.before_request +def _db_connect(): + db.connect() + +# This hook ensures that the connection is closed when we've finished +# processing the request. +@app.teardown_request +def _db_close(exc): + if not db.is_closed(): + db.close() + @app.route('/', methods=['GET']) def root(): query = PPETable.select() #.where(PPETable.is_active == True)