This repository has been archived by the owner on Feb 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
143 lines (114 loc) · 4.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
import datetime
from flask import url_for
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from run import db
from slugify import slugify
from sqlalchemy.exc import IntegrityError
class User(db.Model, UserMixin):
__tablename__ = 'blog_user'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(256), unique=True, nullable=False)
password = db.Column(db.String(128), nullable=False)
is_admin = db.Column(db.Boolean, default=False)
def __repr__(self):
return f'<User {self.email}>'
def set_password(self, password):
"""
To avoid a security problem, instead of saving user passwords, we will save a password HASH using the
werkzeug.security library.
"""
self.password = generate_password_hash(password)
def check_password(self, password):
"""
The check_password method VERIFIES if the hash of the password parameter matches that of the user.
"""
return check_password_hash(self.password, password)
def save(self):
if not self.id:
db.session.add(self)
db.session.commit()
@staticmethod
def get_by_id(id):
"""Query operations on gets"""
return User.query.get(id)
@staticmethod
def get_by_email(email):
return User.query.filter_by(email=email).first()
class Post(db.Model):
"""Up to this point we have implemented all the logic that has to do with blog users. Below we implement
everything related to posts. """
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('blog_user.id', ondelete='CASCADE'), nullable=False)
title = db.Column(db.String(256), nullable=False)
title_slug = db.Column(db.String(256), unique=True, nullable=False)
content = db.Column(db.Text)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
# TRACE (comments) step 3: add a relationship called comments to easily access its list of comments
comments = db.relationship(
'Comment', backref='post', lazy=True, cascade='all, delete-orphan', order_by='asc(Comment.created)')
def __repr__(self):
return f'<Post {self.title}>'
def save(self):
"""We will generate a unique slug of the title automatically using the slugify library."""
if not self.id:
db.session.add(self)
if not self.title_slug:
self.title_slug = slugify(self.title)
saved = False
count = 0
while not saved:
try:
db.session.commit()
saved = True
except IntegrityError:
count += 1
self.title_slug = f'{slugify(self.title)}-{count}'
def delete(self):
db.session.delete(self)
db.session.commit()
def public_url(self):
return url_for('show_post', slug=self.title_slug)
@staticmethod
def get_by_slug(slug):
"""Query operations on posts"""
return Post.query.filter_by(title_slug=slug).first()
@staticmethod
def get_all():
return Post.query.all()
@staticmethod
def get_by_id(id):
return Post.query.get(id)
@staticmethod
def all_paginated(page=1, per_page=20):
return Post.query.order_by(Post.created.asc()). \
paginate(page=page, per_page=per_page, error_out=False)
class Comment(db.Model):
"""
TRACE (comments) step 2: add a new model to save in the database the comments
associated with a post
"""
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('blog_user.id', ondelete='SET NULL'))
user_name = db.Column(db.String)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
content = db.Column(db.Text)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, content, user_id=None, user_name=user_name, post_id=None):
self.content = content
self.user_id = user_id
self.user_name = user_name
self.post_id = post_id
def __repr__(self):
return f'<Comment {self.content}>'
def save(self):
if not self.id:
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
@staticmethod
def get_by_post_id(post_id):
return Comment.query.filter_by(post_id=post_id).all()