From 77eea1c409debccec51b6dd2c49ef5d3ec0e3e79 Mon Sep 17 00:00:00 2001 From: Benjamyn Love Date: Sat, 22 Feb 2020 16:27:16 +1100 Subject: [PATCH 1/5] Moved database calls to there own file --- db.py | 133 ++++++++++++++++++++++++++++++++++++++++ shop.py | 185 +++++++++++--------------------------------------------- 2 files changed, 168 insertions(+), 150 deletions(-) create mode 100644 db.py diff --git a/db.py b/db.py new file mode 100644 index 0000000..ee9cb3c --- /dev/null +++ b/db.py @@ -0,0 +1,133 @@ +import mysql.connector +import configparser + +config = configparser.ConfigParser() + +try: + config.read(".config") +except Exception as E: + print(E) + +def dbConnect(): + mydb = mysql.connector.connect( + host=config["mysql"]["Host"], + user=config["mysql"]["Username"], + passwd=config["mysql"]["Password"], + database=config["mysql"]["Database"] + ) + return mydb + + +def doesTableExist(): + mydb = dbConnect() + mycursor = mydb.cursor() + mycursor.execute('''SHOW TABLES''') + tables = mycursor.fetchall() + if len(tables) == 0: + mycursor.execute('''CREATE TABLE USERS (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255), password VARCHAR(255), admin BOOLEAN)''') + mycursor.execute('''CREATE TABLE LISTS (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))''') + mycursor.execute('''CREATE TABLE SHOPLIST (id INT AUTO_INCREMENT PRIMARY KEY, item VARCHAR(255), gotten BOOLEAN, user_id INT, list_id INT, FOREIGN KEY (`list_id`) REFERENCES `LISTS`(`id`), FOREIGN KEY (`user_id`) REFERENCES `USERS`(`id`) + ON DELETE CASCADE)''') + mycursor.execute('''CREATE TABLE USER_META (user_id INT, list_id INT, FOREIGN KEY (`list_id`) REFERENCES `LISTS`(`id`), FOREIGN KEY (`user_id`) REFERENCES `USERS`(`id`) + ON DELETE CASCADE)''') + mydb.close() + +def runQuery(query, data=None): + mydb = dbConnect() + c = mydb.cursor() + if data is not None: + c.execute(query, data) + else: + c.execute(query) + if query.lower().startswith("select"): + ret = c.fetchall() + else: + ret = [] + mydb.commit() + mydb.close() + return ret + +def readFromDB(): + # By default load all shopping lists the user is a part of (Most users will only have one so this this fine) + query = '''select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username, SHOPLIST.list_id from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id''' + return runQuery(query) + +def insertToDB(data): + query = "INSERT INTO SHOPLIST (item, gotten, user_id, list_id) VALUES (%s, 0, %s, %s)" + data = (data['item'], data['name'], data["list_id"]) + # print(query) + runQuery(query, data) + + +def deleteRow(rowID): + query = "DELETE FROM SHOPLIST WHERE id = %s" + data = (rowID, ) + runQuery(query, data) + +def getItem(rowID): + query = "UPDATE SHOPLIST set gotten = 1 where id = %s" + data = (rowID, ) + runQuery(query, data) + +def unGetItem(rowID): + query = "UPDATE SHOPLIST set gotten = 0 where id = %s" + data = (rowID, ) + runQuery(query, data) + +def get_users(username=None): + if username == None: + #return all users + query = "select username, admin, id from USERS" + return runQuery(query) + query = "select username, admin from USERS where username like %s" + data = (username, ) + return runQuery(query, data) + +def add_user(userData): + username = userData["username"] + password = userData["password"] + query = "insert into USERS (username, password, admin) values (%s, md5(%s), False)" + data = (username, password) + runQuery(query, data) + +def update_pass(user_id, newpass): + query = "update USERS set password=md5(%s) where id=%s" + data = (newpass, user_id) + runQuery(query, data) + +def get_items(user_id, list_id=None): + if list_id != None: + query = "select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id where USER_META.user_id = %s and SHOPLIST.list_id = %s" + data = (user_id, list_id) + return runQuery(query, data) + query = "select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id where USER_META.user_id = %s" + data = (user_id,) + return runQuery(query, data) + +def get_list_ids(user_id): + ret = {} + if user_id == "admin": + query = "SELECT id, name from LISTS;" + res = runQuery(query) + else: + query = "select USER_META.list_id, LISTS.name from USER_META inner join LISTS on LISTS.id = USER_META.list_id where USER_META.user_id = %s" + data = (user_id,) + res = runQuery(query, data) + for lid, name in res: + ret[str(lid)] = name + return ret + +def addList(list_name): + query = "insert into LISTS (name) values (%s)" + data = (list_name,) + runQuery(query, data) + +def addUserToList(userid, listid): + query = "insert into USER_META (user_id, list_id) values (%s, %s)" + data = (userid, listid) + runQuery(query, data) + +def doLogin(username, password): + query = "select id, username, admin from USERS where username = %s and password = md5(%s)" + data = (username, password) + return runQuery(query, data) \ No newline at end of file diff --git a/shop.py b/shop.py index b901858..2fe2792 100644 --- a/shop.py +++ b/shop.py @@ -1,150 +1,42 @@ from flask import Flask, render_template, make_response, request, redirect, url_for, session, abort from pprint import pprint -import mysql.connector -import configparser +import db import os.path -config = configparser.ConfigParser() + MOBILES = ["android", "iphone", "blackberry"] -try: - config.read(".config") -except Exception as E: - print(E) - -def dbConnect(): - mydb = mysql.connector.connect( - host=config["mysql"]["Host"], - user=config["mysql"]["Username"], - passwd=config["mysql"]["Password"], - database=config["mysql"]["Database"] - ) - return mydb - - -def doesTableExist(): - mydb = dbConnect() - mycursor = mydb.cursor() - mycursor.execute('''SHOW TABLES''') - tables = mycursor.fetchall() - if len(tables) == 0: - mycursor.execute('''CREATE TABLE USERS (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255), password VARCHAR(255), admin BOOLEAN)''') - mycursor.execute('''CREATE TABLE LISTS (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))''') - mycursor.execute('''CREATE TABLE SHOPLIST (id INT AUTO_INCREMENT PRIMARY KEY, item VARCHAR(255), gotten BOOLEAN, user_id INT, list_id INT, FOREIGN KEY (`list_id`) REFERENCES `LISTS`(`id`), FOREIGN KEY (`user_id`) REFERENCES `USERS`(`id`) - ON DELETE CASCADE)''') - mycursor.execute('''CREATE TABLE USER_META (user_id INT, list_id INT, FOREIGN KEY (`list_id`) REFERENCES `LISTS`(`id`), FOREIGN KEY (`user_id`) REFERENCES `USERS`(`id`) - ON DELETE CASCADE)''') - mydb.close() - -def runQuery(query, data=None): - mydb = dbConnect() - c = mydb.cursor() - if data is not None: - c.execute(query, data) - else: - c.execute(query) - if query.lower().startswith("select"): - ret = c.fetchall() - else: - ret = [] - mydb.commit() - mydb.close() - return ret - -def readFromDB(): - # By default load all shopping lists the user is a part of (Most users will only have one so this this fine) - query = '''select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username, SHOPLIST.list_id from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id''' - return runQuery(query) - -def insertToDB(data): - query = "INSERT INTO SHOPLIST (item, gotten, user_id, list_id) VALUES (%s, 0, %s, %s)" - data = (data['item'], data['name'], data["list_id"]) - # print(query) - runQuery(query, data) - - -def deleteRow(rowID): - query = "DELETE FROM SHOPLIST WHERE id = %s" - data = (rowID, ) - runQuery(query, data) - -def getItem(rowID): - query = "UPDATE SHOPLIST set gotten = 1 where id = %s" - data = (rowID, ) - runQuery(query, data) - -def unGetItem(rowID): - query = "UPDATE SHOPLIST set gotten = 0 where id = %s" - data = (rowID, ) - runQuery(query, data) - -def get_users(username=None): - if username == None: - #return all users - query = "select username, admin, id from USERS" - return runQuery(query) - query = "select username, admin from USERS where username like %s" - data = (username, ) - return runQuery(query, data) - -def add_user(userData): - username = userData["username"] - password = userData["password"] - query = "insert into USERS (username, password, admin) values (%s, md5(%s), False)" - data = (username, password) - runQuery(query, data) - -def update_pass(user_id, newpass): - query = "update USERS set password=md5(%s) where id=%s" - data = (newpass, user_id) - runQuery(query, data) - -def get_items(user_id, list_id=None): - if list_id != None: - query = "select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id where USER_META.user_id = %s and SHOPLIST.list_id = %s" - data = (user_id, list_id) - return runQuery(query, data) - query = "select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id where USER_META.user_id = %s" - data = (user_id,) - return runQuery(query, data) - -def get_list_ids(user_id): - ret = {} - if user_id == "admin": - query = "SELECT id, name from LISTS;" - res = runQuery(query) - else: - query = "select USER_META.list_id, LISTS.name from USER_META inner join LISTS on LISTS.id = USER_META.list_id where USER_META.user_id = %s" - data = (user_id,) - res = runQuery(query, data) - for lid, name in res: - ret[lid] = name - return ret - -def addList(list_name): - query = "insert into LISTS (name) values (%s)" - data = (list_name,) - runQuery(query, data) - -def addUserToList(userid, listid): - query = "insert into USER_META (user_id, list_id) values (%s, %s)" - data = (userid, listid) - runQuery(query, data) - application = Flask(__name__) application.config["DEBUG"] = True application.secret_key = b'*$#@U9423jr92jioJKL_)_;dasfj()12' +def createSession(res): + list_ids = db.get_list_ids(res[0][0]) + session["id"] = int(res[0][0]) + session["username"] = res[0][1] + session["isAdmin"] = res[0][2] + session["list_ids"] = list_ids + session["active_id"] = "0" + +def refreshSession(id): + list_ids = db.get_list_ids(int(session["id"])) + print(list_ids) + session["list_ids"] = None + session["list_ids"] = list_ids + # print(session["list_ids"]) + @application.route('/') def index(): if session.get('id') is None: data = {"title":"Login"} return render_template("auth.html", data=data) + refreshSession(session["id"]) + if session.get("active_id") == "0": - res = get_items(session["id"]) + res = db.get_items(session["id"]) else: - res = get_items(session["id"], session["active_id"]) + res = db.get_items(session["id"], session["active_id"]) data = {"title": "Shopping List", "results": res, "session": session, "list_ids": session["list_ids"]} for device in MOBILES: @@ -159,41 +51,34 @@ def handle_data(): for x in request.form: if request.form[x] == '': return redirect(url_for('index')) - insertToDB({"item": request.form["item"], "name": session["id"], "list_id": request.form["add2list"]}) + db.insertToDB({"item": request.form["item"], "name": session["id"], "list_id": request.form["add2list"]}) if "rem" in request.form: - deleteRow(request.form["rem"]) + db.deleteRow(request.form["rem"]) if "got" in request.form: - getItem(request.form["got"]) + db.getItem(request.form["got"]) if "ungot" in request.form: - unGetItem(request.form["ungot"]) + db.unGetItem(request.form["ungot"]) if "loginform" in request.form: - query = "select id, username, admin from USERS where username = %s and password = md5(%s)" - data = (request.form["username"].lower(), request.form["password"]) - res = runQuery(query, data) + res = db.doLogin(request.form["username"], request.form["password"]) if len(res) != 0: - list_ids = get_list_ids(res[0][0]) - session["id"] = res[0][0] - session["username"] = res[0][1] - session["isAdmin"] = res[0][2] - session["list_ids"] = list_ids - session["active_id"] = "0" + createSession(res) if "newuser" in request.form: #first check if the user exists - usrCheck = get_users(request.form["username"]) + usrCheck = db.get_users(request.form["username"]) if len(usrCheck) != 0: return "Username Exists" userData = {"username": request.form["username"], "password": request.form["password"]} - add_user(userData) + db.add_user(userData) return redirect(url_for("admin")) if "newpass" in request.form: user_id = request.form['updatepass'] newpass = request.form['newpass'] - update_pass(user_id, newpass) + db.update_pass(user_id, newpass) return redirect(url_for("admin")) if "logout" in request.form: @@ -204,12 +89,12 @@ def handle_data(): if "addList" in request.form: print(request.form["addList"]) - addList(request.form["addList"]) + db.addList(request.form["addList"]) if "add2list" in request.form: userid = request.form["add2list"] listid = request.form["listID"] - addUserToList(userid, listid) + db.addUserToList(userid, listid) return redirect(url_for('index')) @@ -222,12 +107,12 @@ def admin(): return redirect(url_for("index")) #get a list of users - userList = get_users() - lists = get_list_ids("admin") + userList = db.get_users() + lists = db.get_list_ids("admin") data = {"users": userList, "lists": lists} return render_template("admin.html", data=data) if __name__ == '__main__': - doesTableExist() + db.doesTableExist() application.run(host="0.0.0.0") From b1db5e4a17e20dff4e77f81f800ef2b9d126d701 Mon Sep 17 00:00:00 2001 From: Benjamyn Love Date: Sat, 22 Feb 2020 16:27:50 +1100 Subject: [PATCH 2/5] Added '__pycache__' to git ignore Removed id from button --- .gitignore | 1 + templates/index.html | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 9839a7b..883547c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ env/ .vscode/ +__pycache__/ list.db .config \ No newline at end of file diff --git a/templates/index.html b/templates/index.html index 657f4f4..4da94d5 100644 --- a/templates/index.html +++ b/templates/index.html @@ -16,7 +16,7 @@ From 2b98e9db55caa4961b93c403a5964a592fcd2472 Mon Sep 17 00:00:00 2001 From: Benjamyn Love Date: Sat, 22 Feb 2020 16:41:17 +1100 Subject: [PATCH 3/5] Fixed formatting on html pages --- templates/addForm.html | 8 ++-- templates/admin.html | 106 +++++++++++++++++++---------------------- templates/index.html | 37 +++++++------- templates/mobile.html | 37 +++++++------- 4 files changed, 93 insertions(+), 95 deletions(-) diff --git a/templates/addForm.html b/templates/addForm.html index 0c5ad79..74725c1 100644 --- a/templates/addForm.html +++ b/templates/addForm.html @@ -4,9 +4,11 @@

-
+ +
+
\ No newline at end of file diff --git a/templates/admin.html b/templates/admin.html index bf49e87..cf5b203 100644 --- a/templates/admin.html +++ b/templates/admin.html @@ -16,7 +16,12 @@ {{x[0]}} {% if x[1] == 1 %} Yes {% else %} No {% endif %} -
+ +
+ {% endfor %} @@ -25,35 +30,36 @@

ADD NEW USERS

-
+
- +
- -
- -
-
- -
+ +
+ +
+
+ +

ADD LIST

-
+
- +
-
- -
+
+ +
@@ -67,48 +73,36 @@

Add User To List

-
- - - - - -
+
+
+
+ + +
+
+ + +
+ +
+ +
+
+
+
- -
- {% for x in data["lists"] %} - {{data["lists"][x]}} - {% endfor %} diff --git a/templates/index.html b/templates/index.html index 4da94d5..259539d 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,27 +1,28 @@ {% include "header.html" %} -

{{ data["title"] }}, {{data["session"]["username"].title()}} +

{{ data["title"] }}, {{data["session"]["username"].title()}} -

+ {% endif %} + + + +
+
{% include "addForm.html" %} diff --git a/templates/mobile.html b/templates/mobile.html index b4998ee..5016017 100644 --- a/templates/mobile.html +++ b/templates/mobile.html @@ -1,35 +1,38 @@ {% include "header.html" %} - -

{{ data["title"] }}

-

Add User To List

-
+
@@ -93,14 +93,17 @@ {{data["lists"][x]}} {% endfor %} -
- -
+
+
+
+ +
+
From 21d046d4e231bc5fecc68fd55cb4e110cfca4f95 Mon Sep 17 00:00:00 2001 From: Benjamyn Love Date: Sat, 22 Feb 2020 16:46:49 +1100 Subject: [PATCH 5/5] Made color scheme consistent --- static/css/main.css | 5 +++++ templates/admin.html | 10 +++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/static/css/main.css b/static/css/main.css index 33de747..2ee1ca8 100644 --- a/static/css/main.css +++ b/static/css/main.css @@ -30,6 +30,11 @@ aside { color: azure; } +.addlist { + background-color: #2a2a2a; + color: azure; +} + #logbtn { left: 10em; padding-top: 10px; diff --git a/templates/admin.html b/templates/admin.html index 0bdc9ec..f558587 100644 --- a/templates/admin.html +++ b/templates/admin.html @@ -53,7 +53,7 @@
- +
@@ -76,9 +76,9 @@
- +
- - {% for x in data["lists"] %}