コード例 #1
0
class MsgSession(db.Model):
    __tablename__ = 'msg_session'
    id = db.Column(db.Integer, primary_key=True)
    from_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    from_user = db.relationship(User,
                                primaryjoin='User.id==MsgSession.from_id',
                                backref=db.backref(
                                    'from_session',
                                    cascade='all,delete-orphan'))
    to_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    to_user = db.relationship(User,
                              primaryjoin='User.id==MsgSession.to_id',
                              backref=db.backref('to_session',
                                                 cascade='all,delete-orphan'))
    from_read = db.Column(db.Boolean, default=False)
    to_read = db.Column(db.Boolean, default=False)
    count = db.Column(db.Integer, default=1)
    timestamp = db.Column(db.DateTime, index=True)
    msg_contents = db.relationship('MsgContent',
                                   backref='session',
                                   lazy='dynamic')

    def latest_msg(self):
        body = self.msg_contents.filter(
            MsgContent.timestamp == self.timestamp).first()  #不能使用filter_by
        return body.body

    def __repr__(self):
        return '<Session %r>' % (self.to_user)
コード例 #2
0
ファイル: __init__.py プロジェクト: zvrr/ubackup
class BackupInstance(db.Model):
    __tablename__ = 'backup_instance'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    server_id = db.Column(db.String(255), nullable=False)

    backup_type_id = db.Column(db.Integer, db.ForeignKey('backup_type.id'), nullable=False)
    backup_type = db.relationship('BackupType', backref=db.backref('backupinstances', lazy='dynamic'))
    business_id = db.Column(db.Integer, db.ForeignKey('business.id'), nullable=False)
    business = db.relationship('Business', backref=db.backref('backupinstances', lazy='dynamic'))
    instance = db.Column(db.Integer, nullable=False)
コード例 #3
0
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    article_id = db.Column(db.Integer, db.ForeignKey('post.id'))  # 评论文章id
    content = db.Column(db.String(100), nullable=False)
    time = db.Column(db.DateTime,
                     default=datetime.strptime(
                         datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                         '%Y-%m-%d %H:%M:%S'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 用户id
    to_user = db.Column(db.Integer)  # 回复的用户,无则None
    to_id = db.Column(db.Integer)  # 回复目标id,无回复则None  #

    c_post = db.relationship('Post',
                             backref=db.backref('comments',
                                                order_by=id.desc()))
    c_user = db.relationship('User', backref=db.backref('comments'))
コード例 #4
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    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')

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def avatar(self, size):
        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicons&s={}'.format(
            digest, size)
コード例 #5
0
ファイル: __init__.py プロジェクト: zvrr/ubackup
class Node(db.Model):
    __tablename__ = 'node'
    id = db.Column(db.Integer, primary_key=True)
    cluster_id = db.Column(db.Integer, db.ForeignKey('cluster.id'), nullable=False)
    cluster = db.relationship('Cluster', backref=db.backref('nodes', lazy='dynamic'))
    ip = db.Column(db.String(255), unique=True, nullable=False)
    size = db.Column(db.Integer, nullable=False)
    used = db.Column(db.Integer)

    def __repr__(self):
        return '<Node %r>' % self.ip
コード例 #6
0
class Comment(db.Model):
    """
    本文 コメント
    """
    __tablename__ = 'comment'

    id = db.Column(db.Integer, primary_key=True)
    post_on = db.Column(db.DateTime)
    body = db.Column(db.Text)

    post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
    post = db.relation('Post', backref=db.backref('comments', lazy='dynamic'))

    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relation('User',
                         backref=db.backref('comments', lazy='dynamic'))

    def __init__(self, author, body, post_on, post_id):
        self.author = author
        self.post_on = post_on
        self.body = body
        self.post_id = post_id
コード例 #7
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    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',
    )


    def __repr__(self):
        return '<User {}>'.format(self.username) 

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def avatar(self, size):
        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            digest, size)

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)

    def is_following(self, user):
        return self.followed.filter(
            followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        followed = Post.query.join(
            followers, (followers.c.followed_id == Post.user_id)).filter(
                followers.c.follower_id == self.id)
        own = Post.query.filter_by(user_id=self.id)
        return followed.union(own).order_by(Post.timestamp.desc())
コード例 #8
0
class Product(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    price = db.Column(db.Float)
    category_id = db.Column(db.ForeignKey('category.id'))
    category = db.relationship('Category',
                               backref=db.backref('products', lazy='dynamic'))

    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category

    def __repr__(self):
        return '<Product %d>' % self.id
コード例 #9
0
class Post(db.Model):
    """
    本文記事 まわり
    """
    __tablename__ = 'post'

    id = db.Column(db.Integer, primary_key=True)  # :POST ID, PRIMARY
    title = db.Column(db.String(512))
    tag = db.Column(db.String(32))
    body = db.Column(db.Text)
    published_on = db.Column(db.DateTime)

    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relation('User', backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, tag, body, author, published_on):
        self.author = author
        self.title = title
        self.tag = tag
        self.body = body
        self.published_on = published_on
コード例 #10
0
ファイル: models.py プロジェクト: sridvana/flaskblog
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    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')

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def avatar(self, size):
        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            digest, size)

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)

    def is_following(self, user):
        return self.followed.filter(
            followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        followed = Post.query.join(
            followers, (followers.c.followed_id == Post.user_id)).filter(
                followers.c.follower_id == self.id)
        own = Post.query.filter_by(user_id=self.id)
        return followed.union(own).order_by(Post.timestamp.desc())

    def get_reset_password_token(self, expires_in=600):
        return jwt.encode(
            {
                'reset_password': self.id,
                'exp': time() + expires_in
            },
            app.config['SECRET_KEY'],
            algorithm='HS256').decode('utf-8')

    @staticmethod
    def verify_reset_password_token(token):
        try:
            id = jwt.decode(token,
                            app.config['SECRET_KEY'],
                            algorithms=['HS256'])['reset_password']
        except:
            return
        return User.query.get(id)
コード例 #11
0
ファイル: models.py プロジェクト: szwhite1/shayblog
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    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'
    )
    messages_sent = db.relationship('Message', foreign_keys='Message.sender_id', backref='author', lazy='dynamic')
    messages_received = db.relationship('Message', foreign_keys='Message.recipient_id', backref='recipient', lazy='dynamic')
    last_message_read_time = db.Column(db.DateTime)
    notifications = db.relationship('Notification', backref='user', lazy='dynamic')
    tasks = db.relationship('Task', backref='user', lazy='dynamic')

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def avatar(self, size):
        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(digest, size)

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)

    def is_following(self, user):
        return self.followed.filter(followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        followed = Post.query.join(
            followers, (followers.c.followed_id == Post.user_id)).filter(
                followers.c.follower_id == self.id)
        return followed.union(self.posts).order_by(Post.timestamp.desc())

    def get_reset_password_token(self, expires_in=600):
        return jwt.encode(
            {'reset_password': self.id, 'exp': time() + expires_in},
            current_app.config['SECRET_KEY'], algorithm='HS256')

    @staticmethod
    def verify_reset_password_token(token):
        try:
            id = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password']
        except:
            return
        return User.query.get(id)

    def new_messages(self):
        last_read_time = self.last_message_read_time or datetime(1900, 1, 1)
        return Message.query.filter_by(recipient=self).filter(Message.timestamp > last_read_time).count()

    def add_notification(self, name, data):
        self.notifications.filter_by(name=name).delete()
        n = Notification(name=name, payload_json=json.dumps(data), user=self)
        db.session.add(n)
        return n
    
    def launch_task(self, name, description, *args, **kwargs):
        rq_job = current_app.task_queue.enqueue('myapp.tasks.' + name, self.id, *args, **kwargs)
        task = Task(id=rq_job.get_id(), name=name, description=description, user=self)
        db.session.add(task)
        return task

    def get_tasks_in_progress(self):
        return Task.query.filter_by(user=self, complete=False).all()

    def get_task_in_progress(self, name):
        return Task.query.filter_by(name=name, user=self, complete=False).first()
コード例 #12
0
class User(UserMixin, db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    about_me = db.Column(db.String(140))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    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')

    # Assign default role by default, except if registering user
    # is an administrator
    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if self.role is None:
            if self.email in current_app.config['ADMINS']:
                self.role = Role.query.filter_by(
                    permissions=0xff).first()
            if self.role is None:
                self.role = Role.query.filter_by(default=True).first()

    def __repr__(self):
        return '<User: {}>'.format(self.username)

#   #--------------------
#   # User setters
#   #--------------------
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def avatar(self, size):
        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(digest, size)

#   #--------------------
#   # Permissions
#   #--------------------
    def can(self, permissions):
        # Bitwise AND operation checks if the ressource can be
        # accessed by the user
        return self.role is not None and  \
            (self.role.permissions & permissions) == permissions

    def is_admin(self):
        return self.can(Permission.ADMINISTER)

#   #--------------------
#   # Followers
#   #--------------------
    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)

    # Look for items in association table that have the left side foreign
    # key set to the 'self' user, and the right side set to the 'user' argument
    def is_following(self, user):
        return self.followed.filter(
            followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        # Make a temporary joined table that hold all the users that have
        # followers and who have written posts. Then, filter it.
        # The query is issued on the Post class, because a list of posts
        # is returned.
        followed = Post.query.join(
            followers, (followers.c.followed_id == Post.user_id)).filter(
                followers.c.follower_id == self.id)
        own = Post.query.filter_by(user_id=self.id)
        return followed.union(own).order_by(Post.timestamp.desc())

    def get_reset_password_token(self, expires_in=600):
        # jwt encodes the token as a byte sequence, so convert it into
        # a string for convenience.
        return jwt.encode(
            {'reset_password': self.id, 'exp': time() + expires_in},
            current_app.config['SECRET_KEY'],
            algorithm='HS256').decode('utf-8')

    # Static methods can be invoked directly from the class, and do not
    # receive the class as an argument.
    @staticmethod
    def verify_reset_password_token(token):
        # If token is valid, payload is valid and value of reset_password
        # can be used to load the user.
        try:
            id = jwt.decode(token, current_app.config['SECRET_KEY'],
                            algorithms=['HS256'])['reset_password']
        except:
            return
        return User.query.get(id)
コード例 #13
0
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.BigInteger)  # by skyway@14-11-22 随机6位数字+id,防止爬虫
    qq = db.Column(db.String(15), unique=True)
    # 是否加密
    password = db.Column(db.String(50))
    nickname = db.Column(db.String(20))
    sex = db.Column(db.String(5))
    age = db.Column(db.SmallInteger)
    height = db.Column(db.SmallInteger, default=0)
    degree = db.Column(db.String(10))
    condition = db.Column(db.String(10))
    department = db.Column(db.String(20))
    income = db.Column(db.String(10))
    introduce = db.Column(db.String(300))
    # 择偶要求
    requirement = db.Column(db.String(300))
    # 私人信息
    name = db.Column(db.String(30))
    phone = db.Column(db.String(50))
    identity_id = db.Column(db.String(30))
    # 喜欢数
    likes = db.Column(db.Integer, index=True, default=0)
    # 婚姻状态
    status = db.Column(db.String(2))

    # 权限 0:一般用户,1:上传头像用户,……,9:管理员,10:超级管理员
    role = db.Column(db.SmallInteger, default=0)
    avatar_path = db.Column(
        db.String(100), default="http://7u2k3x.com1.z0.glb.clouddn.com/404")
    # back_path = db.Column(db.String(100), default="http://background-thumb.qiniudn.com/404")
    last_seen = db.Column(db.DateTime, default=datetime.datetime.now)
    regtime = db.Column(db.Date, default=datetime.date.today)
    # 关注/粉丝
    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')

    # 私信
    messages = db.relationship('MsgContent', backref='author', lazy='dynamic')
    # 活动参与者
    paticipators = db.relationship('PaticipatorInfo',
                                   backref='actor',
                                   lazy='dynamic')

    # 下面四个method, 都是服务于 flask-login.
    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)

    # 下面四个,关注/好友关系。 模仿microblog,考虑添加“好友” add by lee @ 14.7.25 11:05
    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)
            return self  # 返回的一定是 User 的实例,这样才能 db.session.add(user)  comment by lee  #  狗屁!!

    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

    """这样会执行两次数据库查询。我觉得应该有更好的办法。譬如直接查询followers表?"""

    # add by lee @ 14.7.25 11:23
    def is_friend(self, user):
        return self.is_following(user) and user.is_following(self)

    def __repr__(self):
        return '<User %r>' % self.nickname