class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), nullable=False) author = db.Column(db.String(80)) full_text = db.Column(TEXT, nullable=False) link = db.Column(db.String(250), nullable=False) sessions = db.relationship('Session', secondary=session_articles, lazy='subquery', backref=db.backref('articles', lazy=True)) # many to many def __repr__(self): return f'Article<id={self.id}, title={self.title}, author={self.author}>' def save(self): db.session.add(self) db.session.commit() @classmethod def find_by_id(cls, article_id): return cls.query.filter(cls.id == article_id).first() @classmethod def get_articles(cls): return cls.query.all()
class Course(db.Model): __tablename__ = 'course' code = db.Column(db.String(7), primary_key=True) title = db.Column(db.String(80), nullable=False) credits = db.Column(db.Integer, nullable=False) # many -to many with Users users = db.relationship('User', secondary=course_list, lazy='subquery', backref=db.backref('courses', lazy=True)) sessions = db.relationship('Session', back_populates='course') def __repr__(self): return f'Course<code={self.code}, title={self.title}, credits={self.credits}>' def save(self): db.session.add(self) db.session.commit() @classmethod def get_courses(cls): res = cls.query.all() return res @classmethod def find_by_id(cls, code): course = cls.query.filter(cls.code == code).first() return course
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 Blog(db.Model): __tablename__ = 'blogs' __searchable__ = ['title', 'content'] __analyzer__ = ChineseAnalyzer() id = db.Column(db.Integer, primary_key=True) time = db.Column(db.BigInteger) author = db.Column(db.String(255)) title = db.Column(db.String(255), unique=True) content = db.Column(LONGTEXT) comments = db.relationship('Comment', backref='blogs', lazy='dynamic') tags = db.relationship('Tag', secondary=tags, backref=db.backref('blogs', lazy='dynamic')) def __init__(self, author, title, content): self.author = author self.title = title self.content = content def __repr__(self): return "<Blog '{}'>".format(self.title) def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def to_dict(self): """Transforms a model into a dictionary which can be dumped to JSON.""" # first we get the names of all the columns on your model columns = [c.key for c in class_mapper(self.__class__).columns] # then we return their values in a dict return dict((c, getattr(self, c)) for c in columns) # 返回除了 content, comments 之外的值 @staticmethod def query_title(): sql_str = ''' SELECT blogs.id, blogs.time, blogs.author, blogs.title, group_concat(tags.title) tag FROM blogs LEFT JOIN blog_tags ON blogs.id=blog_tags.blog_id left join tags ON tags.id=blog_tags.tag_id group by blogs.id; ''' ret = db.engine.execute(sql_str).fetchall() return [dict(r) for r in ret]
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 User(db.Model, UserMixin): __tablename__ = 'users' __searchable__ = ['username'] __analyzer__ = ChineseAnalyzer() id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) email = db.Column(db.String(255)) create_time = db.Column(db.String(255)) online = db.Column(db.Boolean, default=False) last_seen_at = db.Column(db.Integer, default=time.time()) updated_at = db.Column(db.Integer, default=time.time(), onupdate=time.time()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) messages = db.relationship('Message', backref='users', lazy='dynamic') def __init__(self, **kwargs): self.username = kwargs['username'] self.password = kwargs['password'] def __repr__(self): return "<User '{}'>".format(self.username) def check_username_password(self, username, password): user = User.query.filter_by(username=username).first() if user is None: return False elif user.password != password: return False else: return True def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() @staticmethod def roll_back(): db.session.rollback() 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) def can(self, permissions): if self.roles is None: return False all_perms = reduce(or_, map(lambda x: x.permissions, self.roles)) return all_perms & permissions == permissions def ping(self): """Marks the user as recently seen and online.""" self.last_seen_at = time.time() last_online = self.online self.online = True return last_online != self.online @staticmethod def get_username_by_reg(reg): sql = ''' select username from users where username REGEXP '{}' LIMIT 5 '''.format(reg) ret = db.engine.execute(sql).fetchall() return [dict(r)['username'] for r in ret] @staticmethod def get_username_limit5(): sql = ''' select username from users LIMIT 5 ''' ret = db.engine.execute(sql).fetchall() return [dict(r)['username'] for r in ret]
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()