-
Notifications
You must be signed in to change notification settings - Fork 0
/
connDB.py
85 lines (67 loc) · 2.44 KB
/
connDB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import psycopg2
DB_HOST = "localhost"
DB_NAME = "livechat_users"
DB_USER = "postgres"
DB_PASS = "admin"
conn = psycopg2.connect(dbname = DB_NAME, user = DB_USER, password = DB_PASS, host = DB_HOST)
cur = conn.cursor()
usersList = list()
class User:
def __init__(self, name, code, password, reports):
self.name = name
self.code = code
self.password = password
self.reports = reports
def getName(self):
return self.name
def getCode(self):
return self.code
def getPassword(self):
return self.password
def getReports(self):
return self.reports
def setReports(self, reports):
self.reports = reports
def loadUsers():
global usersList
cur.execute("SELECT COUNT(*) FROM client")
numPeople = str(cur.fetchone())
numPeople = int(numPeople[1:len(numPeople)-2])
# Inserting the data stored in the DB into the list
for i in range(numPeople):
comm = "SELECT username FROM client WHERE code = " + str(i)
cur.execute(comm)
username = str(cur.fetchone())
username = username[2:-3]
comm = "SELECT password FROM client WHERE code = " + str(i)
cur.execute(comm)
password = str(cur.fetchone())
password = password[2: -3]
comm = "SELECT reports FROM client WHERE code = " + str(i)
cur.execute(comm)
reports = str(cur.fetchone())
try:
reports = int(reports[1:-2])
except:
reports = 0
usersList.append(User(username, i, password, reports))
return usersList, numPeople
def insertUsers(username, password):
global usersList
usersList, numPeople = loadUsers()
cur.execute(f"INSERT INTO client (username, code, password) VALUES ('{username}', {numPeople}, '{password}');")
conn.commit()
usersList.append(User(username, numPeople, password, 0))
loadUsers()
def newReport(userReported):
global usersList
cur.execute(f"UPDATE client SET reports = reports + 1 WHERE username = '{userReported}';")
conn.commit()
cur.execute(f"SELECT code FROM client WHERE username = '{userReported}';")
userCode = str(cur.fetchone())
userCode = int(userCode[1:-2])
totalReports = usersList[userCode].getReports() + 1
usersList[userCode].setReports(totalReports)
return totalReports
def closeConn():
conn.close()