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:
13
src/api.py
13
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)
|
||||
|
||||
Reference in New Issue
Block a user