Moved database calls to there own file
This commit is contained in:
parent
4cada31e5d
commit
77eea1c409
133
db.py
Normal file
133
db.py
Normal file
@ -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)
|
||||||
185
shop.py
185
shop.py
@ -1,150 +1,42 @@
|
|||||||
from flask import Flask, render_template, make_response, request, redirect, url_for, session, abort
|
from flask import Flask, render_template, make_response, request, redirect, url_for, session, abort
|
||||||
from pprint import pprint
|
from pprint import pprint
|
||||||
import mysql.connector
|
import db
|
||||||
import configparser
|
|
||||||
import os.path
|
import os.path
|
||||||
|
|
||||||
config = configparser.ConfigParser()
|
|
||||||
MOBILES = ["android", "iphone", "blackberry"]
|
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 = Flask(__name__)
|
||||||
application.config["DEBUG"] = True
|
application.config["DEBUG"] = True
|
||||||
application.secret_key = b'*$#@U9423jr92jioJKL_)_;dasfj()12'
|
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('/')
|
@application.route('/')
|
||||||
def index():
|
def index():
|
||||||
if session.get('id') is None:
|
if session.get('id') is None:
|
||||||
data = {"title":"Login"}
|
data = {"title":"Login"}
|
||||||
return render_template("auth.html", data=data)
|
return render_template("auth.html", data=data)
|
||||||
|
|
||||||
|
refreshSession(session["id"])
|
||||||
|
|
||||||
if session.get("active_id") == "0":
|
if session.get("active_id") == "0":
|
||||||
res = get_items(session["id"])
|
res = db.get_items(session["id"])
|
||||||
else:
|
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"]}
|
data = {"title": "Shopping List", "results": res, "session": session, "list_ids": session["list_ids"]}
|
||||||
|
|
||||||
for device in MOBILES:
|
for device in MOBILES:
|
||||||
@ -159,41 +51,34 @@ def handle_data():
|
|||||||
for x in request.form:
|
for x in request.form:
|
||||||
if request.form[x] == '':
|
if request.form[x] == '':
|
||||||
return redirect(url_for('index'))
|
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:
|
if "rem" in request.form:
|
||||||
deleteRow(request.form["rem"])
|
db.deleteRow(request.form["rem"])
|
||||||
|
|
||||||
if "got" in request.form:
|
if "got" in request.form:
|
||||||
getItem(request.form["got"])
|
db.getItem(request.form["got"])
|
||||||
|
|
||||||
if "ungot" in request.form:
|
if "ungot" in request.form:
|
||||||
unGetItem(request.form["ungot"])
|
db.unGetItem(request.form["ungot"])
|
||||||
|
|
||||||
if "loginform" in request.form:
|
if "loginform" in request.form:
|
||||||
query = "select id, username, admin from USERS where username = %s and password = md5(%s)"
|
res = db.doLogin(request.form["username"], request.form["password"])
|
||||||
data = (request.form["username"].lower(), request.form["password"])
|
|
||||||
res = runQuery(query, data)
|
|
||||||
if len(res) != 0:
|
if len(res) != 0:
|
||||||
list_ids = get_list_ids(res[0][0])
|
createSession(res)
|
||||||
session["id"] = res[0][0]
|
|
||||||
session["username"] = res[0][1]
|
|
||||||
session["isAdmin"] = res[0][2]
|
|
||||||
session["list_ids"] = list_ids
|
|
||||||
session["active_id"] = "0"
|
|
||||||
|
|
||||||
if "newuser" in request.form:
|
if "newuser" in request.form:
|
||||||
#first check if the user exists
|
#first check if the user exists
|
||||||
usrCheck = get_users(request.form["username"])
|
usrCheck = db.get_users(request.form["username"])
|
||||||
if len(usrCheck) != 0:
|
if len(usrCheck) != 0:
|
||||||
return "Username Exists"
|
return "Username Exists"
|
||||||
userData = {"username": request.form["username"], "password": request.form["password"]}
|
userData = {"username": request.form["username"], "password": request.form["password"]}
|
||||||
add_user(userData)
|
db.add_user(userData)
|
||||||
return redirect(url_for("admin"))
|
return redirect(url_for("admin"))
|
||||||
|
|
||||||
if "newpass" in request.form:
|
if "newpass" in request.form:
|
||||||
user_id = request.form['updatepass']
|
user_id = request.form['updatepass']
|
||||||
newpass = request.form['newpass']
|
newpass = request.form['newpass']
|
||||||
update_pass(user_id, newpass)
|
db.update_pass(user_id, newpass)
|
||||||
return redirect(url_for("admin"))
|
return redirect(url_for("admin"))
|
||||||
|
|
||||||
if "logout" in request.form:
|
if "logout" in request.form:
|
||||||
@ -204,12 +89,12 @@ def handle_data():
|
|||||||
|
|
||||||
if "addList" in request.form:
|
if "addList" in request.form:
|
||||||
print(request.form["addList"])
|
print(request.form["addList"])
|
||||||
addList(request.form["addList"])
|
db.addList(request.form["addList"])
|
||||||
|
|
||||||
if "add2list" in request.form:
|
if "add2list" in request.form:
|
||||||
userid = request.form["add2list"]
|
userid = request.form["add2list"]
|
||||||
listid = request.form["listID"]
|
listid = request.form["listID"]
|
||||||
addUserToList(userid, listid)
|
db.addUserToList(userid, listid)
|
||||||
|
|
||||||
return redirect(url_for('index'))
|
return redirect(url_for('index'))
|
||||||
|
|
||||||
@ -222,12 +107,12 @@ def admin():
|
|||||||
return redirect(url_for("index"))
|
return redirect(url_for("index"))
|
||||||
|
|
||||||
#get a list of users
|
#get a list of users
|
||||||
userList = get_users()
|
userList = db.get_users()
|
||||||
lists = get_list_ids("admin")
|
lists = db.get_list_ids("admin")
|
||||||
data = {"users": userList, "lists": lists}
|
data = {"users": userList, "lists": lists}
|
||||||
|
|
||||||
return render_template("admin.html", data=data)
|
return render_template("admin.html", data=data)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
doesTableExist()
|
db.doesTableExist()
|
||||||
application.run(host="0.0.0.0")
|
application.run(host="0.0.0.0")
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user