microblog/app/models.py

80 lines
2.6 KiB
Python
Raw Normal View History

2012-12-16 08:31:21 +00:00
from hashlib import md5
2012-12-16 08:29:49 +00:00
from app import db
ROLE_USER = 0
ROLE_ADMIN = 1
2012-12-16 08:34:24 +00:00
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
2012-12-16 08:29:49 +00:00
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
2012-12-16 08:30:41 +00:00
nickname = db.Column(db.String(64), unique = True)
2012-12-16 08:29:49 +00:00
email = db.Column(db.String(120), index = True, unique = True)
role = db.Column(db.SmallInteger, default = ROLE_USER)
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')
2012-12-16 08:31:21 +00:00
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
2012-12-16 08:34:24 +00:00
followed = db.relationship('User',
secondary = followers,
primaryjoin = (followers.c.follower_id == id),
secondaryjoin = (followers.c.followed_id == id),
backref = db.backref('followers', lazy = 'dynamic'),
lazy = 'dynamic')
2012-12-16 08:32:38 +00:00
@staticmethod
def make_unique_nickname(nickname):
if User.query.filter_by(nickname = nickname).first() == None:
return nickname
version = 2
while True:
new_nickname = nickname + str(version)
if User.query.filter_by(nickname = new_nickname).first() == None:
break
version += 1
return new_nickname
2012-12-16 08:30:41 +00:00
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
2012-12-16 08:31:21 +00:00
def avatar(self, size):
return 'http://www.gravatar.com/avatar/' + md5(self.email).hexdigest() + '?d=mm&s=' + str(size)
2012-12-16 08:34:24 +00:00
def follow(self, user):
if not self.is_following(user):
self.followed.append(user)
return self
def unfollow(self, user):
if self.is_following(user):
self.followed.remove(user)
return self
def is_following(self, user):
return self.followed.filter(followers.c.followed_id == user.id).count() > 0
def followed_posts(self):
return Post.query.join(followers, (followers.c.followed_id == Post.user_id)).filter(followers.c.follower_id == self.id).order_by(Post.timestamp.desc())
2012-12-16 08:29:49 +00:00
def __repr__(self):
return '<User %r>' % (self.nickname)
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)