-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_helper.py
More file actions
101 lines (83 loc) · 2.37 KB
/
database_helper.py
File metadata and controls
101 lines (83 loc) · 2.37 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import sqlite3
from flask import g
DATABASE = 'database.db'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = make_dicts
return db
def make_dicts(cursor, row):
return dict((cursor.description[idx][0], value)
for idx, value in enumerate(row))
def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
def signup(email, firstname, familyname, city, gender, password, country):
query_db('''
INSERT
INTO users (email, firstname, familyname, city, gender, password, country) VALUES (?, ?, ?, ?, ?, ?, ?)
''', [email, firstname, familyname, city, gender, password, country])
g._database.commit()
def find_user(email):
res = query_db('''
SELECT
email, firstname, familyname, city, gender, country
FROM users WHERE email=?
''', [email], True)
return res
def find_user_with_password(email, password):
res = query_db('''
SELECT
email
FROM users WHERE email=? AND password=?
''', [email, password], True)
return res
def post_message(from_email, to_email, message):
query_db('''
INSERT
INTO posts (from_email, to_email, message) VALUES (?, ?, ?)
''', [from_email, to_email, message])
g._database.commit()
def signin(token, email):
query_db('''
INSERT INTO active_users (token, email) VALUES (?, ?)
''', [token, email])
g._database.commit()
def signout(token):
query_db('''
DELETE FROM active_users WHERE token=?
''', [token])
g._database.commit()
def get_messages(email):
res = query_db('''
SELECT * FROM posts WHERE to_email=?
''', [email])
return res
def email_from_token(token):
res = query_db('''
SELECT email FROM active_users WHERE token=?
''', [token], True)
return res
def update_password(email, password):
query_db('''
UPDATE users SET password=? WHERE email=?
''', [password, email])
g._database.commit()
def total_users():
res = query_db('''
SELECT count(id) FROM users
''', one=True)
return res['count(id)']
def total_messages():
res = query_db('''
SELECT count(id) FROM posts
''', one=True)
return res['count(id)']
def total_user_messges(email):
res = query_db('''
SELECT count(id) FROM posts WHERE to_email=?
''', [email], True)
return res['count(id)']