-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
73 lines (59 loc) · 2.27 KB
/
db.py
File metadata and controls
73 lines (59 loc) · 2.27 KB
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
import sqlite3
class DB:
def __init__(self):
self.conn = sqlite3.connect('users.db', check_same_thread=False)
## self.conn = conn
def get_connection(self):
return self.conn
def __del__(self):
self.conn.close()
class UserModel:
def __init__(self, connection):
self.connection = connection
def init_table(self):
cursor = self.connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR(50),
password_hash VARCHAR(128)
)''')
cursor.close()
self.connection.commit()
def insert(self, user_name, password_hash):
if any([user_name == name for name in map(lambda x: x[1], self.get_all())]):
return False
cursor = self.connection.cursor()
cursor.execute('''INSERT INTO users
(user_name, password_hash)
VALUES (?,?)''', (user_name, password_hash))
cursor.close()
self.connection.commit()
return True
def get(self, user_id):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM users WHERE id = ?", (str(user_id),))
row = cursor.fetchone()
return row
def get_by_name(self, name):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM users WHERE user_name = ?", (str(name),))
row = cursor.fetchone()
return row
def get_all(self):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
return rows
def exists(self, user_name, password_hash):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM users WHERE user_name = ? AND password_hash = ?",
(user_name, password_hash))
row = cursor.fetchone()
return (True, row[0]) if row else (False,)
## def delete_all(self):
## cursor = self.connection.cursor()
## cursor.execute('DELETE FROM users')
## cursor.close()
## self.connection.commit()
##db = DB()
##um = UserModel(db.get_connection())