class User(UserMixin, db.Model): id = db.Column(db.Integer(), primary_key=True) email = db.Column(db.String(64), unique=True, index=True) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) name = db.Column(db.String(64), unique=True) username = db.Column(db.String(255)) password = db.Column(db.String(255)) birthday = db.Column(db.Date()) posts = db.relationship('Post', backref='user', lazy='dynamic') headimg = db.Column(db.String(128), default=None) comments = db.relationship('Comment', backref='user', lazy='dynamic') messagesboard = db.relationship('Messageboard', backref='user', lazy='dynamic') myphotos = db.relationship('Photos', backref='user', lazy='dynamic') def __repr__(self): return "<User '{}'>".format(self.username) def set_password(self, password): self.password = bcrypt.generate_password_hash(password) def check_password(self, password): return bcrypt.check_password_hash(self.password, password) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) db.session.commit()
class Myfeeling(db.Model): id = db.Column(db.Integer(), primary_key=True) text = db.Column(db.Text()) user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) timestamp = db.Column(db.DateTime()) def __repr__(self): return "<My feeling '{}'>".format(self.text[:15])
class Photos(db.Model): id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) timestamp = db.Column(db.DateTime()) pic_url = db.Column(db.Text()) description = db.Column(db.Text()) def __repr__(self): return "<My Photos '{}'".format(self.text[:15])
class Messageboard(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(255)) text = db.Column(db.Text()) timestamp = db.Column(db.DateTime()) user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) def __repr__(self): return "<Messageboard '{}'>".format(self.text[:15])
class Comment(db.Model): id=db.Column(db.Integer(),primary_key = True) name = db.Column(db.String(255)) text = db.Column(db.Text()) date = db.Column(db.DateTime()) post_id = db.Column(db.Integer(),db.ForeignKey('post.id')) def __repr__(self): return "<Comment '{}'>".format(self.text[:15])
class Post(db.Model): id = db.Column(db.Integer(),primary_key=True) title = db.Column(db.String(255)) text = db.Column(db.Text()) publish_date = db.Column(db.DateTime()) user_id = db.Column(db.Integer(),db.ForeignKey('user.id')) comments = db.relationship('Comment',backref = 'post',lazy = 'dynamic') tags=db.relationship( 'Tag',secondary =tags,backref = db.backref('posts',lazy='dynamic') ) def __init__(self,title): self.title = title def __repr__(self): return "<Post '{}'>".format(self.title)
class Post(db.Model): id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(255)) subtitle = db.Column(db.String(255)) text = db.Column(db.Text()) publish_date = db.Column(db.DateTime()) private = db.Column(db.Boolean()) user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) comments = db.relationship('Comment', backref='post', lazy='dynamic') body_html = db.Column(db.Text()) tags = db.relationship('Tag', secondary=tags, backref=db.backref('posts', lazy='dynamic')) ''' @staticmethod def on_changed_body(target,value,oldvalue,intitiator): allowed_tag = ['a','abbr','acronym','b','blockquote','code','div','em','i','li','ol','pre','strong','table','thead','tbody','tr','th','ul','h1','h2','h3','h4','h5','h6','p',] target.body_html = bleach.linkify(bleach.clean(markdown(value,output_html = 'html'),tags=allowed_tag,strip=True)) ''' #处理body字段变化的函数 @staticmethod def on_changed_post(target, value, oldvalue, initiaor): allow_tags = [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p', 'img' ] #转换markdown为html,并清洗html标签 target.body_html = bleach.linkify( bleach.clean( markdown(value, output_form='html', extensions=['extra', 'codehilite']), tags=allow_tags, strip=True, attributes={ '*': ['class'], 'a': ['href', 'rel'], 'img': ['src', 'alt'], #支持<img src …>标签和属性 })) def __repr__(self): return "<Post '{}'>".format(self.title)
class User(db.Model, UserMixin): id = db.Column(db.Integer(), primary_key=True) username = db.Column(db.String(20), unique=True) bio = db.Column(db.String(100)) gender = db.Column(db.SmallInteger(), default=0) # 1 男 2 女 0 未填写 email = db.Column(db.String(50), unique=True, index=True) password = db.Column(db.String(255)) reg_date = db.Column(db.TIMESTAMP(), server_default=func.now()) last_login_date = db.Column(db.DateTime()) wb_uid = db.Column(db.String(20)) avatar = db.Column(db.String(500)) tasks = db.relationship('Task', backref='user', lazy='dynamic') comments = db.relationship('Comment', backref='user', lazy='dynamic') following = db.relationship('User', secondary=follows, primaryjoin=(follows.c.user_id == id), secondaryjoin=(follows.c.follow_id == id), backref=db.backref('follower', lazy='dynamic'), lazy='dynamic') liked = db.relationship('Likes', backref='user', lazy='dynamic') def __init__(self, username): self.username = username def __repr__(self): return '<User: {}>'.format(self.username) # 检查是否关注 def check_following(self, user_id): if User.query.get(user_id) in self.following.all(): return True # 互相关注的好友 def friends(self): return list(set(self.following.all()) & set(self.follower.all())) # 添加关注 def add_following(self, user_id): self.following.append(User.query.get(user_id)) db.session.add(self) db.session.commit() # 取消关注 def cancel_following(self, user_id): self.following.remove(User.query.get(user_id)) db.session.add(self) db.session.commit() def set_password(self, password): self.password = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password, password) def count_task(self): return '创建了{}个任务,完成了{}个'.format( len(self.tasks.all()), len(self.tasks.filter_by(status=1).all())) def unfinish_task(self): return len(self.tasks.all()) - len( self.tasks.filter_by(status=1).all()) # 从微博注册用户 def wb_reg(self, wb_uid): if not User.query.filter_by(wb_uid=wb_uid).first(): self.wb_uid = wb_uid # 查询当前登录用户关注的人中是否有人关注了页面显示的用户 def relation(self): if current_user.username != self.username: return list( set(current_user.following.all()) & set(self.follower.all())) def gender_text(self): return '他' if self.gender else '她' # 取用户头像,为空则取默认头像 def get_avatar(self): if self.avatar: return '/static/images/' + self.avatar else: if self.gender == 0: return '/static/images/0.png' else: return '/static/images/1.png' # 圈子内容 def circle_task(self): query_1 = and_( Task.user_id.in_([user.id for user in self.following.all()]), Task.public_level == '3') if self.following.all() else None # 关注的 query_2 = and_(Task.user_id.in_([ user.id for user in self.friends() ]), Task.public_level == '2') if self.friends() else None # 互相关注的 return Task.query.filter(or_(Task.user_id == self.id, query_1, query_2)).order_by( Task.create_time.desc()).all()
class Task(db.Model): id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id'), nullable=False, index=True) title = db.Column(db.String(100)) text = db.Column(db.Text()) create_time = db.Column(db.TIMESTAMP(), server_default=func.now()) update_time = db.Column(db.DateTime(), onupdate=func.now()) done_time = db.Column(db.DateTime()) deadline = db.Column(db.DateTime(), nullable=False) status = db.Column(db.SmallInteger(), default=0) # 0:进行中 1:已完成 2:暂停 9:删除 public_level = db.Column(db.SmallInteger(), default=3, index=True) # 1:仅自己可见 2:我关注的人可见 3:所有人可见 overtime = db.Column(db.Boolean, default=0) # 任务结束后: 0:未超时 1:超时 comment_allowed = db.Column(db.Boolean, default=1) # 0:禁止评论并隐藏所有评论内容 1:允许评论 comments = db.relationship('Comment', backref='task', lazy='dynamic') liked = db.relationship('Likes', backref='task', lazy='dynamic') def __init__(self, title): self.title = title def __repr__(self): return '<Task: {}|User:{}>'.format(self.title, self.user_id) # 判断任务是否超时 def is_overtime(self): if self.status == 0 and self.deadline > datetime.now(): return False elif self.status == 1 and self.overtime == 0: return False else: return True # 超时时间 def over_time(self): if self.status == 0 and self.deadline < datetime.now(): over_time = datetime.now() - self.deadline if over_time.total_seconds() < 3600: return ''.join( ['已超时', str(int(over_time.total_seconds() / 60)), '分钟']) elif 3600 <= over_time.total_seconds() < 86400: return ''.join( ['已超时', str(int(over_time.total_seconds() / 3600)), '小时']) else: return ''.join( ['已超时', str(int(over_time.total_seconds() / 86400)), '天']) elif self.status == 1: over_time = self.done_time - self.deadline if over_time.total_seconds() < 3600: return ''.join( ['超时', str(int(over_time.total_seconds() / 60)), '分钟完成']) elif 3600 <= over_time.total_seconds() < 86400: return ''.join( ['超时', str(int(over_time.total_seconds() / 3600)), '小时完成']) else: return ''.join( ['超时', str(int(over_time.total_seconds() / 86400)), '天完成']) else: pass # 给任务点赞的所有user_id def liked_user(self): return list(u.user_id for u in self.liked.all()) # 判断是否已点赞 def check_liked(self): if current_user.id in self.liked_user(): return True # 距离超时一小时 def one_hour_deadline(self): the_time = self.deadline - datetime.now() if 0 < the_time.total_seconds() < 3600: return True # 判断当前用户是否有权限查看当前task def task_auth(self): task_user = User.query.get(self.user_id) if current_user.id == self.user_id or self.public_level == 3 or ( current_user in task_user.follower.all() and self.public_level == 2): return True else: return False
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), unique=True, index=True) password = db.Column(db.String(200)) email = db.Column(db.String(200), unique=True, index=True) registered_on = db.Column(db.DateTime, default=datetime.datetime.utcnow) first_name = db.Column(db.String(200)) last_name = db.Column(db.String(200)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) # ========== flask-login methods ========== @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonymous(self): return False def get_id(self): return self.id def get_latest_entry(self, ) -> "JournalEntry": """Return the chronologically latest JournalEntry.""" sess = db.session.object_session(self) if sess is None: try: db.session.add(self) except sqlalchemy.exc.InvalidRequestError: pass return db.session.query(JournalEntry).filter( JournalEntry.owner_id == self.id).order_by( JournalEntry.create_date.desc()).first() def query_all_entries(self): return JournalEntry.query.filter(JournalEntry.owner_id == self.id) def get_all_years(self, ) -> 'iterable[datetime.datetime]': """Return a list of dates corresponding to the range of years encompassed by all journal entries.""" # define earliest and latest years of entries start_year = self.query_all_entries().order_by( JournalEntry.create_date).first() end_year = self.query_all_entries().order_by( JournalEntry.create_date.desc()).first() if start_year and end_year: for y in range(start_year.create_date.year, end_year.create_date.year + 1): # find any entry within this year but before next year found = self.query_all_entries().filter( JournalEntry.create_date >= datetime.datetime( y, 1, 1, 0, 0)).filter( JournalEntry.create_date < datetime.datetime( y + 1, 1, 1, 0, 0)).first() # only yield this year if has an entry if found: yield datetime.datetime(y, 1, 1, 0, 0) def next_entry(self, e: "JournalEntry") -> "JournalEntry": """Return the first JournalEntry that falls chronologically after the given entry.""" return self.query_all_entries().filter( JournalEntry.create_date > e.create_date).first() def previous_entry(self, e: "JournalEntry") -> "JournalEntry": """Return the first JournalEntry that falls chronologically before the given entry.""" return self.query_all_entries().filter( JournalEntry.create_date < e.create_date).order_by( JournalEntry.create_date.desc()).first()