-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
200 lines (171 loc) · 6.23 KB
/
models.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import sqlite3
from datetime import datetime, date
from auth import hash_password, verify_password
from flask_jwt_extended import (create_access_token)
from flask import Flask, request, jsonify
class Schema:
def __init__(self):
self.conn = sqlite3.connect('todo.db')
self.create_user_table()
self.create_to_do_table()
# self.update_user_table()
def __del__(self):
self.conn.commit()
self.conn.close()
def create_to_do_table(self):
query = """
CREATE TABLE IF NOT EXISTS "Todo" (
id INTEGER PRIMARY KEY,
Title TEXT,
Description TEXT,
_is_done boolean DEFAULT 0,
_is_deleted boolean DEFAULT 0,
CreatedOn Date DEFAULT CURRENT_DATE,
DueDate Date,
UserId INTEGER FOREIGNKEY REFERENCES User(_id)
);
"""
self.conn.execute(query)
# def create_user_table(self):
# query = """
# CREATE TABLE IF NOT EXISTS "User" (
# _id INTEGER PRIMARY KEY AUTOINCREMENT,
# Name TEXT,
# Email TEXT,
# CreatedOn Date default CURRENT_DATE
# );
# """
# self.conn.execute(query)
def create_user_table(self):
query = """
CREATE TABLE IF NOT EXISTS `User` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
"""
self.conn.execute(query)
class ToDoModel:
TABLENAME = "Todo"
def __init__(self):
self.conn = sqlite3.connect('todo.db')
self.conn.row_factory = sqlite3.Row
def __del__(self):
# body of destructor
self.conn.commit()
self.conn.close()
def get_by_id(self, _id):
where_clause = f"AND id={_id}"
return self.list_items(where_clause)
def create(self, params):
query = f'insert into {self.TABLENAME} ' \
f'(Title, Description, DueDate, UserId) ' \
f'values ("{params.get("Title")}","{params.get("Description")}",' \
f'"{params.get("DueDate")}","{params.get("UserId")}")'
result = self.conn.execute(query)
return self.get_by_id(result.lastrowid)
def delete(self, item_id):
query = f"UPDATE {self.TABLENAME} " \
f"SET _is_deleted = {1} " \
f"WHERE id = {item_id}"
self.conn.execute(query)
return self.list_items()
def update(self, item_id, update_dict):
"""
column: value
Title: new title
"""
set_query = " ".join([f'{column} = {value}'
for column, value in update_dict.items()])
query = f"UPDATE {self.TABLENAME} " \
f"SET {set_query} " \
f"WHERE id = {item_id}"
self.conn.execute(query)
return self.get_by_id(item_id)
def list_items(self, where_clause=""):
query = f"SELECT id, Title, Description, DueDate, _is_done " \
f"from {self.TABLENAME} WHERE _is_deleted != {1} " + \
where_clause
result_set = self.conn.execute(query).fetchall()
result = [{column: row[i]
for i, column in enumerate(result_set[0].keys())}
for row in result_set]
return result
class UserModel:
TABLENAME = "User"
def __init__(self):
self.conn = sqlite3.connect('todo.db')
self.conn.row_factory = sqlite3.Row
def __del__(self):
# body of destructor
self.conn.commit()
self.conn.close()
def get_by_id(self, _id):
where_clause = f"AND id={_id}"
return self.list_items(where_clause)
def create(self, params):
hashed_password = hash_password(params.get("password"))
query = f'insert into {self.TABLENAME} ' \
f'(Name, Email, CreatedOn, password) ' \
f'values ("{params.get("Name")}","{params.get("Email")}",' \
f'"{datetime.now()}","{hashed_password}")'
result = self.conn.execute(query)
return self.get_by_id(result.lastrowid)
def update(self, item_id, update_dict):
"""
column: value
Name: new name
Email: new email
password: new password
"""
set_query = " ".join([f'{column} = {value}'
for column, value in update_dict.items()])
query = f"UPDATE {self.TABLENAME} " \
f"SET {set_query} " \
f"WHERE _id = {item_id}"
self.conn.execute(query)
return self.get_by_id(item_id)
def list_items(self, where_clause=""):
query = f"SELECT _id, Name, Email, CreatedOn, password " \
f"from {self.TABLENAME} "
result_set = self.conn.execute(query).fetchall()
result = [{column: row[i]
for i, column in enumerate(result_set[0].keys())}
for row in result_set]
return result
def delete(self, item_id):
query = f"DELETE FROM {self.TABLENAME} " \
f"WHERE _id = {item_id}"
self.conn.execute(query)
return self.list_items()
def login(self, params):
email = params.get('Email')
password = params.get('password')
result = ""
query = f'SELECT * FROM User ' \
f'where email = "{email}"'
result_set = self.conn.execute(query).fetchone()
print(result_set)
if verify_password(result_set['password'], password):
access_token = create_access_token(
identity={'Name': result_set['Name'], 'Email': result_set['Email']})
result = {'data': {
'access_token': access_token,
'userData': {
'id': result_set['_id'],
'Name': result_set['Name'],
'Email': result_set['Email'],
'CreatedOn': result_set['CreatedOn']
}
}
}
else:
result = {
"error": "Invalid email and password"
}
print(result)
return result