-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodels.py
178 lines (147 loc) · 5.29 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
import os
from datetime import datetime
from passlib.hash import pbkdf2_sha512
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy.exc
db = SQLAlchemy()
DEFAULT_CATEGORIES = [
'American_action_thriller_films',
'American_biographical_films',
'American_crime_drama_films',
'American_drama_films',
'American_epic_films',
'American_romantic_comedy_films',
'American_satirical_films',
'American_science_fiction_films',
]
MIN_PASSWORD_LENGTH = 8
movielist = db.Table('movielist',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('movie_id', db.Integer, db.ForeignKey('movie.id')),
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
email = db.Column(db.String(512), unique=True, nullable=False)
password_hash = db.Column(db.String(512), nullable=False)
role = db.Column(db.String(512))
movies = db.relationship('Movie', secondary=movielist, backref=db.backref('users', lazy='dynamic'))
def __repr__(self):
return '<User id={!r} username={!r} email={!r}>'.format(self.id, self.username, self.email)
@classmethod
def create(cls, username=None, email=None, password=None, **others):
password_hash = pbkdf2_sha512.encrypt(password)
u = cls(username=username, email=email, password_hash=password_hash)
db.session.add(u)
db.session.commit()
return u
@classmethod
def validate(cls, username_or_email, password):
u = cls.query.filter(
db.or_(cls.username == username_or_email, cls.email == username_or_email)
).one_or_none()
if not u:
raise RuntimeError("Invalid username/email or password.")
if not pbkdf2_sha512.verify(password, u.password_hash):
raise RuntimeError("Invalid username/email or password.")
return u
def add_to_list(self, title):
m = Movie.get_or_create(title)
self.movies.append(m)
db.session.add(self)
db.session.commit()
return m
def remove_from_list(self, title):
self.movies = [m for m in self.movies if m.title != title]
db.session.add(self)
db.session.commit()
def to_json(self):
return dict(
id=self.id,
username=self.username,
)
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(256), unique=True, nullable=False)
def __init__(self, name):
self.name = name
def __unicode__(self):
return self.name
def __repr__(self):
return '<Category id={!r} name={!r}>'.format(self.id, self.name)
@classmethod
def create(cls, name):
c = cls(name)
db.session.add(c)
try:
db.session.commit()
except sqlalchemy.exc.IntegrityError:
raise RuntimeError("Category already exists.")
return c
@classmethod
def load_default_categories(cls):
for c in DEFAULT_CATEGORIES:
db.session.add(cls(c))
db.session.commit()
def to_json(self):
return dict(
id=self.id,
name=self.name,
)
class Movie(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(256), unique=True, nullable=False)
comments = db.relationship('Comment', backref=db.backref('movie', lazy='select'), lazy='dynamic')
@classmethod
def get_or_create(cls, title):
m = cls.query.filter_by(title=title).one_or_none()
if m:
return m
m = cls(title=title)
db.session.add(m)
db.session.commit()
return m
def add_comment(self, comment):
self.comments.append(comment)
db.session.add(self)
db.session.commit()
def __repr__(self):
return '<Movie id={!r} title={!r}>'.format(self.id, self.title)
def to_json(self):
return dict(
id=self.id,
title=self.title,
comments=[row.to_json() for row in self.comments],
)
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
movie_id = db.Column('movie_id', db.Integer, db.ForeignKey('movie.id'))
user_id = db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
contents = db.Column(db.Text, nullable=False)
is_visible = db.Column(db.Boolean, default=False)
is_deleted = db.Column(db.Boolean, default=False)
created = db.Column(db.DateTime, default=datetime.utcnow)
user = db.relationship('User')
def __repr__(self):
return '<Comment id={!r} movie_id={!r} user_id={!r} created={!r} contents={!r}>'.format(
self.id,
self.movie_id,
self.user_id,
self.created,
self.contents if len(self.contents) < 20 else (self.contents[:17] + "..."),
)
def to_json(self):
return dict(
id=self.id,
movie_id=self.movie_id,
user_id=self.user_id,
contents=self.contents,
created=self.created.isoformat(),
)
#####
if __name__ == "__main__":
from app import app
print("Use Category.load_default_categories() to load categories.")
with app.app_context():
db.create_all()
import code; code.interact(local=locals())