Exemplo n.º 1
0
class ChatRoom(BaseModel, db.Model):
    """聊天室表"""
    __tablename__ = 'chat_room'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), comment='聊天室名称', unique=True)
    create_user = db.Column(db.Integer,
                            db.ForeignKey('user.id'),
                            comment='创建人')
    img = db.Column(db.String(256), comment='聊天室封面图')
    desc = db.Column(db.String(512), comment='聊天室简介')
    #中间表中用户
    mid_users = db.relationship('ChatUserRoom',
                                backref='chat_room',
                                lazy='dynamic')
    #跨越中间表的用户
    # users=db.relationship('User',secondary='user_chat_room',
    #                          backref=db.backref('chat_rooms',lazy='dynamic'),lazy='dynamic',cascade='all')
    messages = db.relationship('ChatMessage', backref='room', lazy='dynamic')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_img()

    def set_img(self):
        """设置默认封面图"""
        if not self.img:
            urlFilePath = urljoin('static', 'default/roomDefault.jpg')
            self.img = url_for('static', _external=True, filename=urlFilePath)
Exemplo n.º 2
0
class Role(BaseModel,db.Model):
    """角色"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True,comment='角色名称')
    users = db.relationship('User', back_populates='role')
    permissions = db.relationship('Permission', secondary=roles_permissions,back_populates='roles')

    @staticmethod
    def init_role():
        roles_permissions_map = {
            'Locked': ['FOLLOW'],                       #被封禁用户只可以登录
            'User': ['FOLLOW', 'COLLECT',],             #普通用户可以登录,添加好友
            'Moderator': ['FOLLOW', 'COLLECT',  'MODERATE'],
            'Administrator': ['FOLLOW', 'COLLECT', 'COMMENT',  'MODERATE', 'ADMINISTER']
        }

        for role_name in roles_permissions_map:
            role = Role.query.filter(Role.name==role_name).first()
            if role is None:
                role = Role(name=role_name)
                db.session.add(role)
            role.permissions = []
            for permission_name in roles_permissions_map[role_name]:
                permission = Permission.query.filter_by(name=permission_name).first()
                if permission is None:
                    permission = Permission(name=permission_name)
                    db.session.add(permission)
                role.permissions.append(permission)
        db.session.commit()
Exemplo n.º 3
0
class FeedbackImages(BaseModel, db.Model):
    """反馈问题截图表"""
    __tablename__ = 'feedback_image'

    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(256), nullable=False, comment='反馈图片url链接')
    feedback_id = db.Column(db.Integer,
                            db.ForeignKey('feedback.id'),
                            comment='反馈')
Exemplo n.º 4
0
class chatFriendGroup(BaseModel, db.Model):
    """好友分组表"""
    __tablename__ = 'chat_friend_group'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), comment='用户')
    name = db.Column(db.String(126), comment='好友分组组名')
    group_users = db.relationship('ChatFriend',
                                  backref='group',
                                  lazy='dynamic')
Exemplo n.º 5
0
class ChatMessage(BaseModel, db.Model):
    """聊天消息表"""
    __tablename__ = "chat_message"
    id = db.Column(db.Integer, primary_key=True)
    room_id = db.Column(db.Integer,
                        db.ForeignKey('chat_room.id'),
                        comment='信息发表房间')
    #user_id=db.Column(db.Integer,db.ForeignKey('user.id'),comment='信息发表人')
    user_id = db.Column(db.String(256), comment='信息发表人')
    msg = db.Column(db.String(256), comment='聊天信息')
Exemplo n.º 6
0
class ChatUserRoom(BaseModel, db.Model):
    """聊天室用户中间表"""
    __tablename__ = 'user_chat_room'
    id = db.Column(db.Integer, primary_key=True)
    #user_id=db.Column(db.Integer, db.ForeignKey('user.id'),primary_key=True)
    user_id = db.Column(db.String(256), index=True)
    chat_room_id = db.Column(db.Integer,
                             db.ForeignKey('chat_room.id'),
                             index=True)
    is_create_user = db.Column(db.Boolean, default=False, comment='角色')
Exemplo n.º 7
0
class FeedbackReply(BaseModel, db.Model):
    """反馈问题回复表"""
    __tablename__ = 'feedback_reply'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(128), nullable=False, comment='回复标题')
    content = db.Column(db.TEXT, nullable=False, comment='回复内容')
    user_id = db.Column(db.Integer,
                        db.ForeignKey('user.id'),
                        nullable=False,
                        comment='回复人')
Exemplo n.º 8
0
class FriendsMessage(BaseModel, db.Model):
    """消息表"""
    __tablename__ = 'friends_message'

    class FriendMsgStatus:
        """阅读状态"""
        markRead = 0
        unRead = 1

    id = db.Column(db.Integer, primary_key=True)
    msg = db.Column(db.String(126), comment='聊天记录')
    type = db.Column(db.SmallInteger, default=1, comment='类型')
    from_user_id = db.Column(db.Integer, index=True, comment='发送者')
    to_user_id = db.Column(db.Integer, index=True, comment='接收者')
    status = db.Column(db.SmallInteger, default=1, comment='接收状态')
    room = db.Column(db.String(126), comment='房间名称')

    @staticmethod
    def get_history_message(room):
        """获取单个好友的历史消息"""
        return db.session.query(FriendsMessage).filter(FriendsMessage.room == room,
                                                or_(FriendsMessage.from_user_id == token.id,
                                                    FriendsMessage.to_user_id == token.id),
                                                       FriendsMessage.is_active==True) \
            .order_by(FriendsMessage.create_time.desc())
Exemplo n.º 9
0
    def model(cls, test_id):
        table_index = test_id // 100
        class_name = 'book_%d' % table_index

        ModelClass = getattr(cls.AutoBase.classes, class_name, None)

        if ModelClass is None:
            ModelClass = type(
                class_name, (db.Model, ), {
                    '__module__': __name__,
                    '__name__': class_name,
                    '__tablename__': 'book_%d' % table_index,
                    'id': db.Column(db.Integer, primary_key=True),
                    'desc': db.Column(db.Text, default=None),
                    'test_id': db.Column(db.Integer, index=True)
                })
            db.create_all()
            cls.AutoBase.prepare(db.engine, reflect=True)
        return ModelClass
Exemplo n.º 10
0
class FeedbackType(BaseModel, db.Model):
    """反馈问题类型表"""
    __tablename__ = 'feedback_type'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, comment='反馈类型')
    feedbacks = db.relationship('Feedback',
                                backref=db.backref('feedbackType',
                                                   lazy='joined'),
                                lazy='dynamic')

    @staticmethod
    def init_FeedbackType():
        init_types = ['出现广告信息', '加载速度慢', '功能异常不可用', '页面崩溃打不开']
        for i in init_types:
            Ftype = FeedbackType.query.filter(FeedbackType.name == i).first()
            if Ftype is None:
                Ftype = FeedbackType(name=i)
                db.session.add(Ftype)
        db.session.commit()
Exemplo n.º 11
0
class ChatFriend(BaseModel, db.Model):
    """好友审核表"""
    __tablename__ = 'chat_friend'

    class ChatFriendStatus(enum.Enum):
        """审核状态"""
        NOT_PASS = 0
        PASS = 1
        WAIT = 2
        LOSE = 3

    id = db.Column(db.Integer, primary_key=True)
    self_id = db.Column(db.Integer, index=True, comment='自己')
    friend_id = db.Column(db.Integer, index=True, comment='好友')
    status = db.Column(db.SmallInteger, default=2, comment='审核状态')
    remark = db.Column(db.String(126), comment='名称备注')
    top = db.Column(db.Boolean, default=False, comment='置顶')
    become_friends_time = db.Column(db.DATETIME, comment='成为好友的时间')
    group_id = db.Column(db.Integer,
                         db.ForeignKey('chat_friend_group.id'),
                         comment='分组')
    room = db.Column(db.String(126), comment='房间名称')
    initiator_id = db.Column(db.Integer, comment='发起人')

    @staticmethod
    def get_friends_id():
        """获取好友字典"""
        friends = db.session.query(ChatFriend.friend_id, ChatFriend).filter(
            ChatFriend.self_id == token.id, ChatFriend.is_active == True,
            ChatFriend.status == 1).all()
        return {str(i[0]): i[1].to_dict() for i in friends}

    @staticmethod
    def check_is_friend(friend_id):
        if db.session.query(ChatFriend).filter(
                ChatFriend.self_id == token.id,
                ChatFriend.friend_id == friend_id,
                ChatFriend.is_active == True, ChatFriend.status == 1).first():
            return True
        return False
Exemplo n.º 12
0
class Feedback(BaseModel, db.Model):
    """反馈问题"""
    __tablename__ = 'feedback'

    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.TEXT, nullable=False, comment='反馈内容')
    contact = db.Column(db.String(128), comment='反馈联系方式')
    type_id = db.Column(db.Integer,
                        db.ForeignKey('feedback_type.id'),
                        comment='反馈类型')
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), comment='创建人')
    reply_id = db.Column(db.Integer,
                         db.ForeignKey('feedback_reply.id'),
                         comment='官方回复')
    image = db.Column(db.String(256), comment='反馈问题截图封面')
    images = db.relationship('FeedbackImages',
                             lazy='dynamic',
                             backref=db.backref('feedback', lazy='joined'))
Exemplo n.º 13
0
class User(BaseModel,db.Model):
    """用户表"""
    __tablename__='user'

    USER_SEX = (
        (0, 'women'),
        (1, 'man'),
        (2, 'secrecy')
    )
    id=db.Column(Integer,primary_key=True)
    userName=db.Column(String(64),nullable=False,unique=True,comment='用户名')
    pwd=db.Column(String(256),nullable=False,comment='密码')
    nickName=db.Column(String(64),nullable=False,comment='昵称')
    #需手动修改migrate表文件
    sex = db.Column(ChoiceType(USER_SEX, SmallInteger()), comment='性别',default=2)
    birth=db.Column(DATE,comment='生日')
    portrait=db.Column(String(256), comment='头像',nullable=False)
    email=db.Column(String(128),unique=True,comment='邮箱')
    is_email=db.Column(Boolean,comment='认证邮箱',default=False)
    province=db.Column(String(64),comment='省份')
    city=db.Column(String(64),comment='城市')
    home=db.Column(String(64),comment='地区')
    role_id=db.Column(Integer,db.ForeignKey('role.id'))
    friends_strategy_id=db.Column(db.Integer,db.ForeignKey('friends_strategy.id'),comment='添加好友策略')


    #用了back_populates,另一张表也必须指明!
    role = db.relationship('Role', back_populates='users',lazy='joined')
    # #我的反馈
    feedback=db.relationship('Feedback',lazy='dynamic',backref=db.backref('user',lazy='joined'))
    #我的反馈回复
    feedbackReply=db.relationship('FeedbackReply',lazy='dynamic',backref=db.backref('user',lazy='joined'))
    #我创建的聊天室
    MychatRooms=db.relationship('ChatRoom',lazy='dynamic',backref='founder')

    # from apps.friend.model import ChatFriend
    # # 我的所有好友
    # friends=db.relationship('ChatFriend',lazy='dynamic',backref='user',
    #                         foreign_keys='ChatFriend.self_id')

    #lazy="dynamic",懒加载,用到时才会去查询
    #lazy="select",直接查询
    #lazy="joined",连表查询
    #lazy="subquery": 与joined类似,但使用子子查询
    #db.backref('_class',lazy="dynamic"), lazy="dynamic")
    #areas = db.relationship("Area", backref="users", secondary=user_area,lazy='dynamic')

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        self.set_role()
        self.set_portrait()
        self.password_hash=self.pwd

    def __repr__(self):
        return self.userName

    @property
    def platform(self):
        ua = request.user_agent.platform or ''
        if 'android' in ua or 'Linux' in ua:
            return 0
        elif 'iphone' in ua:
            return 1
        else:
            return 2


    @property
    def is_admin(self):
        return self.role.name == 'Administrator'

    @property
    def password_hash(self):
        raise AttributeError('only setter attribute')

    @password_hash.setter
    def password_hash(self,value):
        self.pwd=generate_password_hash(value)

    def check_password(self,pwd):
        return check_password_hash(self.pwd,pwd)

    def to_dict(self,values=None):
        data=super().to_dict(values)
        data.pop('pwd')
        data['pre']='user'
        return data

    def set_role(self):
        """设置默认角色"""
        if self.role is None:
            if self.email == current_app.config['ADMIN_EMAIL']:
                self.role = Role.query.filter_by(name='Administrator').first()
            else:
                self.role = Role.query.filter_by(name='User').first()

    def set_portrait(self):
        """设置默认头像"""
        if not self.portrait:
            self.portrait = 'https://img.yzcdn.cn/vant/cat.jpeg'

    def can(self, permission_name):
        permission = Permission.query.filter_by(name=permission_name).first()
        return permission is not None and self.role is not None and permission in self.role.permissions
Exemplo n.º 14
0
class Permission(BaseModel,db.Model):
    """权限"""
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True,comment='权限名称')
    roles = db.relationship('Role', secondary=roles_permissions, back_populates='permissions',lazy='joined')
Exemplo n.º 15
0
                }

    @property
    def platform(self):
        ua = request.user_agent.platform or ''
        if 'android' in ua or 'Linux' in ua:
            return 0
        elif 'iphone' in ua:
            return 1
        else:
            return 2


#角色权限中间表
roles_permissions = db.Table('roles_permissions',
                             db.Column('role_id', db.Integer, db.ForeignKey('role.id')),
                             db.Column('permission_id', db.Integer, db.ForeignKey('permission.id'))
                             )


class User(BaseModel,db.Model):
    """用户表"""
    __tablename__='user'

    USER_SEX = (
        (0, 'women'),
        (1, 'man'),
        (2, 'secrecy')
    )
    id=db.Column(Integer,primary_key=True)
    userName=db.Column(String(64),nullable=False,unique=True,comment='用户名')
Exemplo n.º 16
0
class TestModel(db.Model):
    __tablename__ = 'test'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, nullable=False)
Exemplo n.º 17
0
class FriendsStrategy(BaseModel, db.Model):
    """添加好友策略"""
    __tablename__ = 'friends_strategy'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(126), comment='添加好友策略')
    user = db.relationship('User', backref='friends_strategy', lazy='dynamic')