forked from TTP-Group1/flask_blog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
64 lines (50 loc) · 2.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
from puppycompanyblog import db,login_manager
from datetime import datetime
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
# By inheriting the UserMixin we get access to a lot of built-in attributes
# which we will be able to call in our views!
# is_authenticated()
# is_active()
# is_anonymous()
# get_id()
# The user_loader decorator allows flask-login to load the current user
# and grab their id.
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
class User(db.Model, UserMixin):
# Create a table in the db
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
profile_image = db.Column(db.String(20), nullable=False, default='default_profile.png')
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
# This connects BlogPosts to a User Author.
posts = db.relationship('BlogPost', backref='author', lazy=True)
def __init__(self, email, username, password):
self.email = email
self.username = username
self.password_hash = generate_password_hash(password)
def check_password(self,password):
# https://stackoverflow.com/questions/23432478/flask-generate-password-hash-not-constant-output
return check_password_hash(self.password_hash,password)
def __repr__(self):
return f"UserName: {self.username}"
class BlogPost(db.Model):
# Setup the relationship to the User table
users = db.relationship(User)
# Model for the Blog Posts on Website
id = db.Column(db.Integer, primary_key=True)
# Notice how we connect the BlogPost to a particular author
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
title = db.Column(db.String(140), nullable=False)
text = db.Column(db.Text, nullable=False)
def __init__(self, title, text, user_id):
self.title = title
self.text = text
self.user_id =user_id
def __repr__(self):
return f"Post Id: {self.id} --- Date: {self.date} --- Title: {self.title}"