-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
95 lines (67 loc) · 2.71 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
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt()
db = SQLAlchemy()
class User(db.Model):
"""User model."""
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
favorite_characters = db.relationship('FavoriteCharacter', backref='user', lazy=True)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return str(self.id)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
@classmethod
def register(cls, username, password, email):
"""Register a user, hashing their password."""
hashed = Bcrypt.generate_password_hash(password)
hashed_utf8 = hashed.decode("utf8")
user = cls(
username=username,
password=hashed_utf8,
email=email
)
db.session.add(user)
return user
@classmethod
def authenticate(cls, username, password):
"""Find user with `username` and `password`.
This is a class method (call it on the class, not an individual user.)
It searches for a user whose password hash matches this password
and, if it finds such a user, returns that user object.
If can't find matching user (or if password is wrong), returns False.
"""
user = cls.query.filter_by(username=username).first()
if user:
is_auth = bcrypt.check_password_hash(user.password, password)
if is_auth:
return user
return False
class FavoriteCharacter(db.Model):
"""FavoriteCharacter model."""
__tablename__ = 'favorite_character'
id = db.Column(db.Integer, primary_key=True)
character_id = db.Column(db.Integer, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
added_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
name = db.Column(db.String, nullable=False)
image_url = db.Column(db.String, nullable=True)
def __repr__(self):
return f"FavoriteCharacter('{self.name}','{self.character_id}', '{self.user_id}')"
@classmethod
def is_favorite(cls, user_id, character_id):
return db.session.query(cls).filter_by(user_id=user_id, character_id=character_id).first() is not None
def connect_db(app):
"""Connect this database to Flask app."""
db.app = app
db.init_app(app)