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
This commit is contained in:
2024-07-21 16:54:33 +02:00
parent ae1bcf84d5
commit 7d41f00cce

View File

@@ -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)