From 0cd026559952417c4a83f590f13b5a0e9bba624a Mon Sep 17 00:00:00 2001 From: Marek Baczynski Date: Fri, 30 Nov 2018 20:47:43 +0100 Subject: [PATCH 1/2] fixed database connection --- kukv1.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/kukv1.py b/kukv1.py index 6a7e437..87f872d 100644 --- a/kukv1.py +++ b/kukv1.py @@ -4,6 +4,7 @@ import json import datetime from flask import Flask, Response, redirect, url_for, request, session, abort, render_template from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user +import sqlalchemy from sqlalchemy.sql import select, text from dateutil.parser import parse app = Flask(__name__) @@ -36,18 +37,19 @@ def getUpcomingMeals(): query = 'select username as kuk, meal_date, array_agg as eaters, selection_deadline from (select kuk, meal_date, selection_deadline, array_agg(username) from meals join users on users.id = any(meals.eaters) where meals.status=0 group by meals.id order by meal_date) as foo join users on kuk=users.id;' r = db_engine.execute(text(query)) meals = [] - for row in r: - meals.append(dict(row)) - r.close() + for row in r: + meals.append(dict(row)) + r.close() return meals @app.route('/') def index(): return render_template('meal_list.html', leaderboard=getLeaderboard(), meals=getUpcomingMeals(), current_user_name='Wille') -if __name__ == '__main__': - with open('admin.json') as f: - postgres_credentials = json.load(f) +with open('admin.json') as f: + postgres_credentials = json.load(f) db_engine, db_metadata = connect(postgres_credentials['username'], postgres_credentials['password'], 'kuk_app') meals = sqlalchemy.Table('meals', db_metadata) + +if __name__ == '__main__': app.run('0.0.0.0') \ No newline at end of file From 35e577424aab03974d06765e093aa575401ad3be Mon Sep 17 00:00:00 2001 From: Marek Baczynski Date: Fri, 30 Nov 2018 20:47:54 +0100 Subject: [PATCH 2/2] leaderboard but not good yet --- kukv1.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/kukv1.py b/kukv1.py index 87f872d..720bd0f 100644 --- a/kukv1.py +++ b/kukv1.py @@ -20,10 +20,20 @@ db_engine = {} db_metadata = {} meals = {} +def connect(user, password, db, host='localhost', port=5432): + url = 'postgresql://{}:{}@{}:{}/{}' + url = url.format(user, password, host, port, db) + con = sqlalchemy.create_engine(url, client_encoding='utf8') + meta = sqlalchemy.MetaData(bind=con, reflect=True) + return con, meta + def getLeaderboard(): - leaders = [] - leaders.append({'name':'marek', 'score':34}) - leaders.append({'name':'sven', 'score':16}) + s = 'select u.username as name, u.score as score, max(m.meal_date) as last_meal from users as u inner join meals as m on u.id = m.kuk where m.kuk>0 and m.status>0 group by u.id order by u.score, last_meal;' + r = db_engine.execute(text(s)) + leaders=[] + for row in r: + leaders.append(dict(row)) + r.close() return leaders def getUpcomingMeals():