-
Notifications
You must be signed in to change notification settings - Fork 463
Expand file tree
/
Copy pathmodels.py
More file actions
409 lines (345 loc) · 14.9 KB
/
models.py
File metadata and controls
409 lines (345 loc) · 14.9 KB
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
#coding: utf-8
import hashlib
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask.ext.login import UserMixin
from . import db, login_manager
from jieba.analyse import ChineseAnalyzer
article_types = {u'开发语言': ['Python', 'Java', 'JavaScript'],
'Linux': [u'Linux成长之路', u'Linux运维实战', 'CentOS', 'Ubuntu'],
u'网络技术': [u'思科网络技术', u'其它'],
u'数据库': ['MySQL', 'Redis'],
u'爱生活,爱自己': [u'生活那些事', u'学校那些事',u'感情那些事'],
u'Web开发': ['Flask', 'Django'],}
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
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))
avatar_hash = db.Column(db.String(32))
userlevel = db.Column(db.String(32))
@staticmethod
def insert_admin(email, username, password, userlevel):
user = User(email=email, username=username, password=password, userlevel=userlevel)
db.session.add(user)
db.session.commit()
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
if self.email is not None and self.avatar_hash is None:
self.avatar_hash = hashlib.md5(
self.email.encode('utf-8')).hexdigest()
def gravatar(self, size=40, default='identicon', rating='g'):
# if request.is_secure:
# url = 'https://secure.gravatar.com/avatar'
# else:
# url = 'http://www.gravatar.com/avatar'
url = 'http://gravatar.duoshuo.com/avatar'
hash = self.avatar_hash or hashlib.md5(
self.email.encode('utf-8')).hexdigest()
return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
url=url, hash=hash, size=size, default=default, rating=rating)
# callback function for flask-login extentsion
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class Menu(db.Model):
__tablename__ = 'menus'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
types = db.relationship('ArticleType', backref='menu', lazy='dynamic')
order = db.Column(db.Integer, default=0, nullable=False)
def sort_delete(self):
for menu in Menu.query.order_by(Menu.order).offset(self.order).all():
menu.order -= 1
db.session.add(menu)
@staticmethod
def insert_menus():
menus = [u'Web开发', u'数据库', u'网络技术', u'爱生活,爱自己',
u'Linux世界', u'开发语言']
for name in menus:
menu = Menu(name=name)
db.session.add(menu)
db.session.commit()
menu.order = menu.id
db.session.add(menu)
db.session.commit()
@staticmethod
def return_menus():
menus = [(m.id, m.name) for m in Menu.query.all()]
menus.append((-1, u'不选择导航(该分类将单独成一导航)'))
return menus
def __repr__(self):
return '<Menu %r>' % self.name
class ArticleTypeSetting(db.Model):
__tablename__ = 'articleTypeSettings'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
protected = db.Column(db.Boolean, default=False)
hide = db.Column(db.Boolean, default=False)
types = db.relationship('ArticleType', backref='setting', lazy='dynamic')
@staticmethod
def insert_system_setting():
system = ArticleTypeSetting(name='system', protected=True, hide=True)
db.session.add(system)
db.session.commit()
@staticmethod
def insert_default_settings():
system_setting = ArticleTypeSetting(name='system', protected=True, hide=True)
common_setting = ArticleTypeSetting(name='common', protected=False, hide=False)
db.session.add(system_setting)
db.session.add(common_setting)
db.session.commit()
@staticmethod
def return_setting_hide():
return [(2, u'公开'), (1, u'隐藏')]
def __repr__(self):
return '<ArticleTypeSetting %r>' % self.name
class ArticleType(db.Model):
__tablename__ = 'articleTypes'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
introduction = db.Column(db.Text, default=None)
articles = db.relationship('Article', backref='articleType', lazy='dynamic')
menu_id = db.Column(db.Integer, db.ForeignKey('menus.id'), default=None)
setting_id = db.Column(db.Integer, db.ForeignKey('articleTypeSettings.id'))
@staticmethod
def insert_system_articleType():
articleType = ArticleType(name=u'未分类',
introduction=u'系统默认分类,不可删除。',
setting=ArticleTypeSetting.query.filter_by(protected=True).first()
)
db.session.add(articleType)
db.session.commit()
@staticmethod
def insert_articleTypes():
articleTypes = ['Python', 'Java', 'JavaScript', 'Django',
'CentOS', 'Ubuntu', 'MySQL', 'Redis',
u'Linux成长之路', u'Linux运维实战', u'其它',
u'思科网络技术', u'生活那些事', u'学校那些事',
u'感情那些事', 'Flask']
for name in articleTypes:
articleType = ArticleType(name=name,
setting=ArticleTypeSetting(name=name))
db.session.add(articleType)
db.session.commit()
@property
def is_protected(self):
if self.setting:
return self.setting.protected
else:
return False
@property
def is_hide(self):
if self.setting:
return self.setting.hide
else:
return False
# if the articleType does not have setting,
# its is_hie and is_protected property will be False.
def __repr__(self):
return '<Type %r>' % self.name
class Source(db.Model):
__tablename__ = 'sources'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
articles = db.relationship('Article', backref='source', lazy='dynamic')
@staticmethod
def insert_sources():
sources = (u'原创',
u'转载',
u'翻译')
for s in sources:
source = Source.query.filter_by(name=s).first()
if source is None:
source = Source(name=s)
db.session.add(source)
db.session.commit()
def __repr__(self):
return '<Source %r>' % self.name
class Follow(db.Model):
__tablename__ = 'follows'
follower_id = db.Column(db.Integer, db.ForeignKey('comments.id'),
primary_key=True)
followed_id = db.Column(db.Integer, db.ForeignKey('comments.id'),
primary_key=True)
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
author_name = db.Column(db.String(64))
author_email = db.Column(db.String(64))
avatar_hash = db.Column(db.String(32))
article_id = db.Column(db.Integer, db.ForeignKey('articles.id'))
disabled = db.Column(db.Boolean, default=False)
comment_type = db.Column(db.String(64), default='comment')
reply_to = db.Column(db.String(128), default='notReply')
followed = db.relationship('Follow',
foreign_keys=[Follow.follower_id],
backref=db.backref('follower', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
followers = db.relationship('Follow',
foreign_keys=[Follow.followed_id],
backref=db.backref('followed', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
def __init__(self, **kwargs):
super(Comment, self).__init__(**kwargs)
if self.author_email is not None and self.avatar_hash is None:
self.avatar_hash = hashlib.md5(
self.author_email.encode('utf-8')).hexdigest()
def gravatar(self, size=40, default='identicon', rating='g'):
# if request.is_secure:
# url = 'https://secure.gravatar.com/avatar'
# else:
# url = 'http://www.gravatar.com/avatar'
url = 'http://gravatar.duoshuo.com/avatar'
hash = self.avatar_hash or hashlib.md5(
self.author_email.encode('utf-8')).hexdigest()
return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
url=url, hash=hash, size=size, default=default, rating=rating)
@staticmethod
def generate_fake(count=100):
from random import seed, randint
import forgery_py
seed()
article_count = Article.query.count()
for i in range(count):
a = Article.query.offset(randint(0, article_count - 1)).first()
c = Comment(content=forgery_py.lorem_ipsum.sentences(randint(3, 5)),
timestamp=forgery_py.date.date(True),
author_name=forgery_py.internet.user_name(True),
author_email=forgery_py.internet.email_address(),
article=a)
db.session.add(c)
try:
db.session.commit()
except:
db.session.rollback()
@staticmethod
def generate_fake_replies(count=100):
from random import seed, randint
import forgery_py
seed()
comment_count = Comment.query.count()
for i in range(count):
followed = Comment.query.offset(randint(0, comment_count - 1)).first()
c = Comment(content=forgery_py.lorem_ipsum.sentences(randint(3, 5)),
timestamp=forgery_py.date.date(True),
author_name=forgery_py.internet.user_name(True),
author_email=forgery_py.internet.email_address(),
article=followed.article, comment_type='reply',
reply_to=followed.author_name)
f = Follow(follower=c, followed=followed)
db.session.add(f)
db.session.commit()
def is_reply(self):
if self.followed.count() == 0:
return False
else:
return True
# to confirm whether the comment is a reply or not
def followed_name(self):
if self.is_reply():
return self.followed.first().followed.author_name
class Article(db.Model):
__searchable__ = ['id','title', 'content', 'summary']
__tablename__ = 'articles'
__analyzer__ = ChineseAnalyzer()
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(64), unique=True)
content = db.Column(db.Text)
summary = db.Column(db.Text)
create_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
update_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
num_of_view = db.Column(db.Integer, default=0)
articleType_id = db.Column(db.Integer, db.ForeignKey('articleTypes.id'))
source_id = db.Column(db.Integer, db.ForeignKey('sources.id'))
comments = db.relationship('Comment', backref='article', lazy='dynamic')
@staticmethod
def generate_fake(count=100):
from sqlalchemy.exc import IntegrityError
from random import seed, randint
import forgery_py
seed()
articleType_count = ArticleType.query.count()
source_count = Source.query.count()
for i in range(count):
aT = ArticleType.query.offset(randint(0, articleType_count - 1)).first()
s = Source.query.offset(randint(0, source_count - 1)).first()
a = Article(title=forgery_py.lorem_ipsum.title(randint(3, 5)),
content=forgery_py.lorem_ipsum.sentences(randint(15, 35)),
summary=forgery_py.lorem_ipsum.sentences(randint(2, 5)),
num_of_view=randint(100, 15000),
articleType=aT, source=s)
db.session.add(a)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
@staticmethod
def add_view(article, db):
article.num_of_view += 1
db.session.add(article)
db.session.commit()
def __repr__(self):
return '<Article %r>' % self.title
class BlogInfo(db.Model):
__tablename__ = 'blog_info'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(64))
signature = db.Column(db.Text)
navbar = db.Column(db.String(64))
@staticmethod
def insert_blog_info():
blog_mini_info = BlogInfo(title=u'开源博客系统Blog_mini',
signature=u'让每个人都轻松拥有可管理的个人博客!— By xpleaf',
navbar='inverse')
db.session.add(blog_mini_info)
db.session.commit()
class Plugin(db.Model):
__tablename__ = 'plugins'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(64), unique=True)
note = db.Column(db.Text, default='')
content = db.Column(db.Text, default='')
order = db.Column(db.Integer, default=0)
disabled = db.Column(db.Boolean, default=False)
@staticmethod
def insert_system_plugin():
plugin = Plugin(title=u'博客统计',
note=u'系统插件',
content='system_plugin',
order=1)
db.session.add(plugin)
db.session.commit()
def sort_delete(self):
for plugin in Plugin.query.order_by(Plugin.order.asc()).offset(self.order).all():
plugin.order -= 1
db.session.add(plugin)
def __repr__(self):
return '<Plugin %r>' % self.title
class BlogView(db.Model):
__tablename__ = 'blog_view'
id = db.Column(db.Integer, primary_key=True)
num_of_view = db.Column(db.BigInteger, default=0)
@staticmethod
def insert_view():
view = BlogView(num_of_view=0)
db.session.add(view)
db.session.commit()
@staticmethod
def add_view(db):
view = BlogView.query.first()
view.num_of_view += 1
db.session.add(view)
db.session.commit()