-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
497 lines (398 loc) · 15.5 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
"""Models for NewSmart app."""
import datetime
from flask import flash
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from logger import logger
db = SQLAlchemy()
DEFAULT_IMG_URL = "static/images/question-mark.jpg"
NEWS_CATEGORIES = ("business", "entertainment", "general",
"health", "science", "sports", "technology")
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.Text, nullable=False)
email = db.Column(db.String(50), nullable=False, unique=True)
first_name = db.Column(db.String(30), nullable=False)
last_name = db.Column(db.String(30), nullable=False)
saves = db.relationship('Saves', backref='user', passive_deletes=True)
articles = db.relationship('Article', secondary="saves", lazy="joined",
backref='users')
users_categories = db.relationship('UserCategory', backref='user', passive_deletes=True)
categories = db.relationship('Category', secondary="users_categories", backref='users')
bcrypt = Bcrypt()
@classmethod
def register(cls, username, password, email, first_name, last_name):
"""
Register user w/hashed password & commit to db.
Return user object if successful, otherwise return None.
"""
hashed = cls.bcrypt.generate_password_hash(password)
# turn bytestring into normal (unicode utf8) string
hashed_utf8 = hashed.decode("utf8")
new_user = cls(
username=username, password=hashed_utf8, email=email,
first_name=first_name, last_name=last_name
)
try:
db.session.add(new_user)
db.session.commit()
except IntegrityError:
flash("Username/email already exist.", "danger")
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(f'Failed to create {new_user} on database.')
flash(f"Failed to create '{username}'", "danger")
db.session.rollback()
return None
return new_user
@classmethod
def update(cls, old_username, new_username, password):
"""
Update user with specified id & commit to db.
Return user object if successful, otherwise return None.
"""
user = User.authenticate(old_username, password)
if not user:
flash("Username and password do not match!", 'danger')
return None
user.username = new_username
try:
db.session.add(user)
db.session.commit()
except IntegrityError:
flash("Username already exists.", "danger")
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(f'Failed to update {user} on database.')
flash(f"Failed to update '{username}'", "danger")
db.session.rollback()
return None
return user
@classmethod
def authenticate(cls, username, pwd):
"""
Validate that user exists & password is correct.
Return user if valid; else return None.
"""
user = cls.query.filter_by(username=username).first()
if user and cls.bcrypt.check_password_hash(user.password, pwd):
# return user instance
return user
else:
return None
def __repr__(self):
return (f"<User: username='{self.username}' "
f"email='{self.email}' "
f"first_name={self.first_name} "
f"last_name={self.last_name}>")
@property
def full_name(self):
return f"{self.first_name} {self.last_name}"
class Article(db.Model):
__tablename__ = "articles"
id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
title = db.Column(db.Text, nullable=False)
summary = db.Column(db.Text)
content = db.Column(db.Text, nullable=False)
url = db.Column(db.Text, nullable=False, unique=True)
source = db.Column(db.Text, nullable=False)
img_url = db.Column(db.Text, nullable=False, default=DEFAULT_IMG_URL)
timestamp = db.Column(db.DateTime, nullable=False,
default=datetime.datetime.utcnow())
saves = db.relationship('Saves', backref='article', passive_deletes=True)
articles_tags = db.relationship('ArticleTag', backref='article', passive_deletes=True)
@classmethod
def new(cls, title, content, url, source, summary=None, img_url=None, timestamp=None):
"""
Create new article object and commit to db.
Return article object if successful, otherwise return None.
Note: articles can only be added internally currently, no UI.
"""
new_article = cls(
title=title, summary=summary, content=content,
url=url, source=source, img_url=img_url, timestamp=timestamp
)
try:
db.session.add(new_article)
db.session.commit()
except IntegrityError:
logger.error(f"Cannot add {new_article} to database; URL already exists.")
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(f'Failed to create {new_article} on database.')
db.session.rollback()
return None
return new_article
def __repr__(self):
return (f"<Article: id={self.id} "
f"title={self.title if len(self.title) < 20 else '...'} "
f"url={self.url if len(self.url) < 20 else '...'} "
f"source={self.source} "
f"timestamp={self.timestamp} "
f"has_summary={'yes' if self.summary else 'no'}>")
def serialize(self):
return {
"id": self.id,
"title": self.title,
"summary": self.summary,
"content": self.content,
"url": self.url,
"source": self.source,
"img_url": self.img_url,
"timestamp": self.timestamp.isoformat(),
}
class Tag(db.Model):
__tablename__ = "tags"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
keyword = db.Column(db.String(32), nullable=False, unique=True)
articles_tags = db.relationship('ArticleTag', backref='tag', passive_deletes=True)
articles = db.relationship('Article', secondary="articles_tags", backref='tags')
@classmethod
def new(cls, keyword):
"""
Create new tag object and commit to db.
Return tag object if successful, otherwise return None.
Note: tags can only be added internally, no UI.
"""
new_tag = cls(keyword=keyword)
try:
db.session.add(new_tag)
db.session.commit()
except IntegrityError:
logger.warning(
f"Cannot add {new_tag} to database; keyword already exists."
)
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(f'Failed to create {new_tag} on database.')
db.session.rollback()
return None
return new_tag
def __repr__(self):
return (f"<Tag: id={self.id} "
f"keyword='{self.keyword}'>")
def serialize(self):
return {
"id": self.id,
"keyword": self.keyword,
}
class Category(db.Model):
__tablename__ = "categories"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(32), nullable=False, unique=True)
users_categories = db.relationship('UserCategory', backref='category', passive_deletes=True)
@classmethod
def new(cls, name):
"""
Create new tag object and commit to db.
Return tag object if successful, otherwise return None.
Note: tags can only be added internally, no UI.
"""
new_category = cls(name=name)
try:
db.session.add(new_category)
db.session.commit()
except IntegrityError:
logger.warning(
f"Cannot add {new_category} to database; URL already exists."
)
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(f'Failed to create {new_category} on database.')
db.session.rollback()
return None
return new_category
def __repr__(self):
return (f"<Category: id={self.id} "
f"name='{self.name}'>")
def serialize(self):
return {
"id": self.id,
"name": self.name,
}
# Intermediate tables for many-to-many relationship
class Saves(db.Model):
__tablename__ = "saves"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
# delete record if any parents get removed
user_id = db.Column(db.Integer,
db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
article_id = db.Column(db.Integer,
db.ForeignKey('articles.id', ondelete='CASCADE'), nullable=False)
timestamp = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow())
__table_args__ = (
db.UniqueConstraint('user_id', 'article_id', name='unique_bookmark'),
)
@classmethod
def new(cls, user_id, article_id, timestamp=None):
"""
Create new saves object and commit to db.
Return saves object if successful, otherwise return None.
Note: saves object can only be added internally, no UI.
"""
new_saves = cls(user_id=user_id, article_id=article_id, timestamp=timestamp)
try:
db.session.add(new_saves)
db.session.commit()
except IntegrityError as e:
logger.error(
f"Cannot add {new_saves} to database. {e.orig.pgerror}"
)
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(f'Failed to create {new_saves} on database.')
db.session.rollback()
return None
return new_saves
@classmethod
def remove(cls, saves_id):
"""
Remove saves object and commit to db.
Return True if successful, otherwise return False.
"""
saves = cls.query.get_or_404(saves_id)
try:
db.session.delete(saves)
db.session.commit()
except SQLAlchemyError:
logger.critical(f'Failed to delete {saves} from database.')
db.session.rollback()
return False
return True
def __repr__(self):
return (f"<Saves: user_id={self.user_id} article_id='{self.article_id}'>")
def serialize(self):
return {
"id": self.id,
"user_id": self.user_id,
"article_id": self.article_id,
"timestamp": self.timestamp.isoformat(),
}
class ArticleTag(db.Model):
__tablename__ = "articles_tags"
# delete record if any parents get removed
article_id = db.Column(db.Integer,
db.ForeignKey('articles.id', ondelete='CASCADE'),
primary_key=True)
tag_id = db.Column(db.Integer,
db.ForeignKey('tags.id', ondelete='CASCADE'),
primary_key=True)
@classmethod
def new(cls, article_id, tag_id):
"""
Create new article-tag object and commit to db.
Return article-tag object if successful, otherwise return None.
Note: article-tag object can only be added internally, no UI.
"""
new_article_tag = cls(article_id=article_id, tag_id=tag_id)
try:
db.session.add(new_article_tag)
db.session.commit()
except IntegrityError:
logger.error(
f"Cannot add {new_article_tag} to database; URL already exists."
)
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(
f'Failed to create {new_article_tag} on database.')
db.session.rollback()
return None
return new_article_tag
def __repr__(self):
return (f"<Article-Tag: article={self.article_id} tag_id='{self.tag_id}'>")
def serialize(self):
return {
"article_id": self.article_id,
"tag_id": self.tag_id,
}
class UserCategory(db.Model):
__tablename__ = "users_categories"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
# delete record if any parents get removed
user_id = db.Column(db.Integer,
db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
category_id = db.Column(db.Integer,
db.ForeignKey('categories.id', ondelete='CASCADE'), nullable=False)
__table_args__ = (
db.UniqueConstraint('user_id', 'category_id', name='unique_users_catgories'),
)
@classmethod
def new(cls, user_id, category_id):
"""
Create new user-category object and commit to db.
Return user-category object if successful, otherwise return None.
"""
new_user_category = cls(user_id=user_id, category_id=category_id)
try:
db.session.add(new_user_category)
db.session.commit()
except IntegrityError:
logger.error(
f"Cannot add {new_user_category} to database; URL already exists."
)
db.session.rollback()
return None
except SQLAlchemyError:
logger.critical(
f'Failed to create {new_user_category} on database.')
db.session.rollback()
return None
return new_user_category
@classmethod
def remove(cls, user_id, category_id):
"""
Remove user-category association object and commit to db.
Return True if successful, otherwise return False.
"""
user_category = cls.query.filter(
UserCategory.user_id == user_id, UserCategory.category_id == category_id
).first_or_404()
try:
db.session.delete(user_category)
db.session.commit()
except SQLAlchemyError:
logger.critical(f'Failed to delete {user_category} from database.')
db.session.rollback()
return False
return True
@classmethod
def remove_user(cls, user_id):
"""
Remove user-category association object and commit to db.
Return True if successful, otherwise return False.
"""
try:
user_category = cls.query.filter(
UserCategory.user_id == user_id).delete()
db.session.commit()
except SQLAlchemyError:
logger.critical(f'Failed to delete {user_category} from database.')
db.session.rollback()
return False
return True
def __repr__(self):
return (f"<User-Category: user_id={self.user_id} category_id='{self.category_id}'>")
def serialize(self):
return {
"id": self.id,
"user_id": self.user_id,
"category_id": self.category_id,
}
def connect_db(app):
"""
Connect this database to provided Flask app.
You should call this in your Flask app.
"""
db.app = app
db.init_app(app)