class Post(db.Model): """Post model define.""" __tablename__ = "posts" id = db.Column(db.Integer, primary_key=True) topic_id = db.Column( db.Integer, db.ForeignKey("topics.id", use_alter=True, name="fk_post_topic_id", ondelete="CASCADE")) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True) username = db.Column(db.String(200), nullable=False) content = db.Column(db.Text, nullable=False) def save(self, user=None, topic=None): """Save a new post. If no parameters are passed we assume that you will just update an existing post. It returns the object after the operation was successful. :param user: The user who has created the post :param topic: The topic in which the post was created """ self.user_id = user.id self.username = user.username self.topic_id = topic.id db.session.add(self) db.session.commit()
class Forum(db.Model): """Forum model define.""" __tablename__ = "forums" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) description = db.Column(db.Text) position = db.Column(db.Integer, default=1, nullable=False) category_id = db.Column(db.Integer, db.ForeignKey("categories.id"), nullable=False) groups = db.relationship( "Group", secondary=forumgroups, primaryjoin=(forumgroups.c.forum_id == id), backref="forumgroups", lazy="joined", ) def save(self, groups=None): """Save the object to the database.""" from lucheng.user.models import Group if groups is None: self.groups = Group.query.order_by(Group.name.asc()).all() db.session.add(self) db.session.commit() return self
class Topic(db.Model): """Topic model define.""" __tablename__ = "topics" id = db.Column(db.Integer, primary_key=True) forum_id = db.Column(db.Integer, db.ForeignKey("forums.id", use_alter=True, name="fk_topic_forum_id"), nullable=False) title = db.Column(db.String(255), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) username = db.Column(db.String(200), nullable=False) def save(self, user=None, forum=None, post=None): """ Save a topic and returns the topic object. If no parameters are given, it will only update the topic. :param user: The user who has created the topic :param forum: The forum where the topic is stored :param post: The post object which is connected to the topic """ # Updates the topic if self.id: db.session.add(self) db.session.commit() return self # Set the forum and user id self.forum_id = forum.id self.user_id = user.id self.username = user.username # Insert and commit the topic db.session.add(self) db.session.commit() # Create the topic post post.save(user, self)
class Category(db.Model): """Category model define.""" __tablename__ = "categories" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) description = db.Column(db.Text) position = db.Column(db.Integer, default=1, nullable=False) # one to many forums = db.relationship("Forum", backref="category", lazy="dynamic", primaryjoin='Forum.category_id == Category.id', order_by='asc(Forum.position)', cascade='all, delete-orphan') def save(self): """Save the object to the database.""" db.session.add(self) db.session.commit() return self @classmethod def get_all(cls, user): """Get all categories with all associated forums. It returns a list with tuples. Those tuples are containing the category and their associated forums (whose are stored in a list). For example:: [(<Category 1>, [(<Forum 2>, <ForumsRead>), (<Forum 1>, None)]), (<Category 2>, [(<Forum 3>, None), (<Forum 4>, None)])] :param user: The user object is needed to check if we also need their forumsread object. """ if user.is_authenticated: from lucheng.user.models import Group # forums = Forum.query.subquery() # get list of user group ids user_groups = [group.id for group in user.groups] # filter forums by user groups user_forums = Forum.query.\ filter(Forum.groups.any(Group.id.in_(user_groups))).subquery() forum_alias = aliased(Forum, user_forums) query_result = cls.query.\ join(forum_alias, cls.id == forum_alias.category_id).\ add_entity(forum_alias).\ all() # print(query_result) else: query_result = cls.query.join(Forum, cls.id == Forum.category_id).\ add_entity(Forum).\ all() forums = [] it = itertools.groupby(query_result, operator.itemgetter(0)) for key, value in it: forums.append((key, [item[1] for item in value])) return forums
""" forum model define file. Forum Category and so on """ import itertools import operator from sqlalchemy.orm import aliased from lucheng.extensions import db # m2m table for group-forum permission mapping forumgroups = db.Table( 'forumgroups', db.Column('group_id', db.Integer(), db.ForeignKey('groups.id'), nullable=False), db.Column('forum_id', db.Integer(), db.ForeignKey('forums.id', use_alter=True, name="fk_forum_id"), nullable=False)) class Forum(db.Model): """Forum model define.""" __tablename__ = "forums" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) description = db.Column(db.Text)
class User(db.Model, UserMixin): """User define.""" __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(200), unique=True, nullable=False) email = db.Column(db.String(200), unique=True, nullable=False) def _get_password(self): """Return the hashed password.""" return self._password def _set_password(self, password): """Check password, If password match it returns True, else False.""" if password is None: return False self._password = generate_password_hash(password) _password = db.Column('password', db.String(120), nullable=False) password = db.synonym('_password', descriptor=property(_get_password, _set_password)) activated = db.Column(db.Boolean, default=False) primary_group_id = db.Column(db.Integer, db.ForeignKey('groups.id'), nullable=False) primary_group = db.relationship('Group', lazy="joined", backref="user_group", uselist=False, foreign_keys=[primary_group_id]) secondary_groups = db.relationship( 'Group', secondary=groups_users, primaryjoin=(groups_users.c.user_id == id), backref=db.backref('users', lazy='dynamic'), lazy='dynamic') # Methods def __repr__(self): """Set to a unique key specific to the object in the database. Required for cache.memoize() to work across requests. """ return "<{} {}>".format(self.__class__.__name__, self.username) def save(self): """Save the object to the database.""" db.session.add(self) db.session.commit() return self def check_password(self, password): """Check passwords. If passwords match it returns true, else false.""" if self.password is None: return False return check_password_hash(self.password, password) @property def groups(self): """Return the user groups.""" return [self.primary_group] + list(self.secondary_groups) '''
class Group(db.Model): """Group define.""" __tablename__ = "groups" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), unique=True, nullable=False) description = db.Column(db.Text) # Group types admin = db.Column(db.Boolean, default=False, nullable=False) super_mod = db.Column(db.Boolean, default=False, nullable=False) mod = db.Column(db.Boolean, default=False, nullable=False) guest = db.Column(db.Boolean, default=False, nullable=False) banned = db.Column(db.Boolean, default=False, nullable=False) # Moderator permissions (only available when the user a moderator) mod_edituser = db.Column(db.Boolean, default=False, nullable=False) mod_banuser = db.Column(db.Boolean, default=False, nullable=False) # User permissions editpost = db.Column(db.Boolean, default=True, nullable=False) deletepost = db.Column(db.Boolean, default=False, nullable=False) deletetopic = db.Column(db.Boolean, default=False, nullable=False) posttopic = db.Column(db.Boolean, default=True, nullable=False) postreply = db.Column(db.Boolean, default=True, nullable=False) # Methods def __repr__(self): """ Set to a unique key specific to the object in the database. Required for cache.memoize() to work across requests. """ return "<{} {} {}>".format(self.__class__.__name__, self.id, self.name) def save(self): """Save the object to the database.""" db.session.add(self) db.session.commit() return self
""" summary: models.py. description: xxx """ from werkzeug.security import (generate_password_hash, check_password_hash) from flask_login import UserMixin from lucheng.extensions import db groups_users = db.Table( 'groups_users', db.Column('group_id', db.Integer(), db.ForeignKey('groups.id')), db.Column('user_id', db.Integer(), db.ForeignKey('users.id'))) class Group(db.Model): """Group define.""" __tablename__ = "groups" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), unique=True, nullable=False) description = db.Column(db.Text) # Group types admin = db.Column(db.Boolean, default=False, nullable=False) super_mod = db.Column(db.Boolean, default=False, nullable=False) mod = db.Column(db.Boolean, default=False, nullable=False) guest = db.Column(db.Boolean, default=False, nullable=False) banned = db.Column(db.Boolean, default=False, nullable=False)