Add database connection to global context so repeat queries dont recreate connections(Need to check if this actually improves speed) also added in logic so if add workout is triggered when there is already a workout on that day without any topsets it will instead load that

This commit is contained in:
Peter Stockings
2023-08-06 13:34:33 +10:00
parent 8e26cbf281
commit 5ccb1f1905
2 changed files with 40 additions and 10 deletions

5
app.py
View File

@@ -384,6 +384,11 @@ def get_workout_note(person_id, workout_id):
return render_template('partials/workout_note.html', person_id=person_id, workout_id=workout_id, note=workout['Note']) return render_template('partials/workout_note.html', person_id=person_id, workout_id=workout_id, note=workout['Note'])
@app.teardown_appcontext
def closeConnection(exception):
db.close_connection()
@app.template_filter('list_to_string') @app.template_filter('list_to_string')
def list_to_string(list): def list_to_string(list):
return [str(i) for i in list] return [str(i) for i in list]

33
db.py
View File

@@ -3,6 +3,8 @@ import psycopg2
from psycopg2.extras import RealDictCursor from psycopg2.extras import RealDictCursor
from datetime import datetime from datetime import datetime
from urllib.parse import urlparse from urllib.parse import urlparse
from flask import g
from utils import get_all_exercises_from_topsets, get_stats_from_topsets, get_workouts from utils import get_all_exercises_from_topsets, get_stats_from_topsets, get_workouts
@@ -10,26 +12,41 @@ from utils import get_all_exercises_from_topsets, get_stats_from_topsets, get_wo
class DataBase(): class DataBase():
def __init__(self, app): def __init__(self, app):
db_url = urlparse(os.environ['DATABASE_URL']) db_url = urlparse(os.environ['DATABASE_URL'])
# if db_url is null then throw error
if not db_url:
raise Exception("No DATABASE_URL environment variable set")
self.conn = psycopg2.connect( def getDB(self):
db = getattr(g, 'database', None)
if db is None:
db_url = urlparse(os.environ['DATABASE_URL'])
g.database = psycopg2.connect(
database=db_url.path[1:], database=db_url.path[1:],
user=db_url.username, user=db_url.username,
password=db_url.password, password=db_url.password,
host=db_url.hostname, host=db_url.hostname,
port=db_url.port port=db_url.port
) )
db = g.database
return db
def close_connection(exception):
db = getattr(g, 'database', None)
if db is not None:
db.close()
def execute(self, query, args=(), one=False, commit=False): def execute(self, query, args=(), one=False, commit=False):
cur = self.conn.cursor(cursor_factory=RealDictCursor) conn = self.getDB()
cur = conn.cursor(cursor_factory=RealDictCursor)
cur.execute(query, args) cur.execute(query, args)
rv = None rv = None
if cur.description is not None: if cur.description is not None:
rv = cur.fetchall() rv = cur.fetchall()
if commit: if commit:
try: try:
self.conn.commit() conn.commit()
except: except:
self.conn.rollback() conn.rollback()
cur.close() cur.close()
return (rv[0] if rv else None) if one else rv return (rv[0] if rv else None) if one else rv
@@ -119,6 +136,14 @@ class DataBase():
def create_workout(self, person_id): def create_workout(self, person_id):
now = datetime.now() now = datetime.now()
date_string = now.strftime('%Y-%m-%d') date_string = now.strftime('%Y-%m-%d')
# check if a workout has already been created for this person today that doesnt contain any topsets and if so return the WorkoutId
workout = self.execute('SELECT workout_id AS "WorkoutId" FROM workout WHERE person_id=%s AND start_date=%s AND workout_id NOT IN (SELECT workout_id FROM topset)', [
person_id, date_string], one=True)
if workout:
print(
f'Workout already created for PersonId {person_id} starting at {date_string} so returning WorkoutId {workout["WorkoutId"]} rather then creating new workout')
return workout['WorkoutId']
print( print(
f'Creating workout for PersonId {person_id} starting at {date_string}') f'Creating workout for PersonId {person_id} starting at {date_string}')
new_workout = self.execute('INSERT INTO workout (person_id, start_date) VALUES (%s, %s) RETURNING workout_id AS "WorkoutId"', [ new_workout = self.execute('INSERT INTO workout (person_id, start_date) VALUES (%s, %s) RETURNING workout_id AS "WorkoutId"', [