Ejemplo n.º 1
0
class User(UserMixin, db.Model):  #通过继承db.Model创建class User
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True,
                         index=True)  #加上index是因为速度会快一些
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    about_me = db.Column(db.String(128))
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    tweets = db.relationship(
        'Tweet', backref='author',
        lazy='dynamic')  #这里的'Tweet'里的,用来了解一个用户发了多少个推特,不是表中的一列

    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):  #为了调试方便创建的函数,打印一个实例或者在shell显示
        return 'id={},username={},email={},password_hash={}'.format(
            self.id, self.username, self.email, self.password_hash)

    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=80):
        md5_digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            md5_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 own_and_followed_tweets(self):
        followed = Tweet.query.join(
            followers, (followers.c.followed_id == Tweet.user_id)).filter(
                followers.c.follower_id == self.id)
        own = Tweet.query.filter_by(user_id=self.id)
        return followed.union(own).order_by(Tweet.create_time.desc())
Ejemplo n.º 2
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    tweets = db.relationship('Tweet', backref='author', lazy='dynamic')

    def __repr__(self):
        return 'id={},username={},email={},password_hash={}'.format(
            self.id, self.username, self.email, self.password_hash)
Ejemplo n.º 3
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    about_me = db.Column(db.String(256))
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    is_activated = db.Column(db.Boolean, default=False)

    tweets = db.relationship('Tweet', backref='author', lazy='dynamic')
    """ 这里Tweet是大写"""

    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 'id = {}, username = {}, email = {}, password_hash = {}'.format(
            self.id, self.username, self.email, self.password_hash)

    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=80):
        md5_digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            md5_digest, size)

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

    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 own_and_followed_tweets(self):
        own = Tweet.query.filter_by(user_id=self.id)  #我自己的tweets
        #我follow的人的tweets
        #这里的followers是上面那张follower|followed的关系表
        followed = Tweet.query.join(
            followers, (followers.c.follower_id == self.id)).filter(
                Tweet.user_id == followers.c.followed_id)
        #两张表join在一起
        return followed.union(own).order_by(Tweet.create_time.desc())

    def get_jwt(self, expire=7200):
        return jwt.encode(
            {
                'email': self.email,
                'exp': time.time() + expire  #time limit
            },
            current_app.config['SECRET_KEY'],
            algorithm='HS256').decode('utf-8')
        #如果不decode,产生的会是一个binary string

    #做成一个静态的方法,因为我们不希望使用的时候还需要去实例化一个user对象\
    #一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。\
    #而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。\
    #这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。\
    #因为我们可以去route里面看到: user : User.verify_jwt(token)\
    #这时候我们是通过User这个class去调用的这个方法,而我们并不知道是哪一个用户,我们只能通过verify这个方法\
    #去帮我们返回User.query.filter_by(email = email).first 用户的实力\
    @staticmethod
    def verify_jwt(token):
        try:
            email = jwt.decode(token,
                               current_app.config['SECRET_KEY'],
                               algorithms='HS256')
            email = email['email']
        except:
            return
        return User.query.filter_by(email=email).first()
Ejemplo n.º 4
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    about_me = db.Column(db.String(120))
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    is_activated = db.Column(db.Boolean, default=False)

    tweets = db.relationship('Tweet', 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 'id={}, username={}, email={}, password_hash={}'.format(
            self.id, self.username, self.email, self.password_hash)

    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=80):
        md5_digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            md5_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 own_and_followed_tweets(self):
        followed = Tweet.query.join(
            followers, (followers.c.followed_id == Tweet.user_id)).filter(
                followers.c.follower_id == self.id)
        own = Tweet.query.filter_by(user_id=self.id)
        return followed.union(own).order_by(Tweet.create_time.desc())

    def get_jwt(self, expire=7200):
        return jwt.encode({
            'email': self.email,
            'exp': time.time() + expire
        },
                          current_app.config['SECRET_KEY'],
                          algorithm='HS256').decode('utf-8')

    @staticmethod
    def verify_jwt(token):
        try:
            email = jwt.decode(token,
                               current_app.config['SECRET_KEY'],
                               algorithms=['HS256'])
            email = email['email']
        except:
            return
        return User.query.filter_by(email=email).first()
Ejemplo n.º 5
0
class User(UserMixin, db.Model):  #讓User繼承UserMixin的方法
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True,
                         index=True)  # unique=True全域唯一
    email = db.Column(db.String(64), unique=True, index=True)
    #unique=True全域唯一  有加index搜索會比較快
    password_hash = db.Column(db.String(128))
    phone = db.Column(db.String(32))
    tax = db.Column(db.String(32))
    about_me = db.Column(db.String(256))
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    is_activated = db.Column(db.Boolean, default=False)

    tweets = db.relationship("Tweet", backref="author", lazy="dynamic")
    #不在資料表裡面而是連Tweet資料表 用來計算用戶發了多少文 1對多

    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 'id={},username={}, email={}, password_hash={}'.format(
            self.id, self.username, self.email, self.password_hash)

    #設定回傳的資料
    #測試 再命令列打from twittor.models import User
    #user = User(username='******',email='*****@*****.**',password_hash='12345')
    #id用Nane 以後自動生成 每次自動加1
    #user 可以測試剛生成的

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        #生成密碼的hash值

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
        #比較檢查資料庫裡的密碼和用戶輸入的密碼 正確符合回傳True

    def avatar(self, size=80):
        md5_digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            md5_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
        #對過濾後的結果再過濾 如果是1的話代表已經follow

    def own_and_followed_tweets(self):
        followed = Tweet.query.join(  #從數據庫中所有的文
            followers, (followers.c.followed_id == Tweet.user_id)).filter(
                followers.c.follower_id == self.id)  #篩選出關注的人的推文
        own = Tweet.query.filter_by(user_id=self.id)  #本人發的推文
        return followed.union(own).order_by(Tweet.create_time.desc())
        #把篩選出關注的貼文和本人的發文union結合 排列order_by依據發文時間 desc降序(最新的在最前)

    def get_jwt(self, expire=7200):  #編碼給用戶的密碼重設
        return jwt.encode(
            {
                'email': self.email,
                'exp': time.time() + expire
            },  #exp用於超時
            current_app.config['SECRET_KEY'],
            algorithm='HS256').decode('utf-8')  #修正格式

    @staticmethod  #做成靜態方法 因為此時還不知道是哪個用戶
    def verify_jwt(token):
        try:
            email = jwt.decode(token,
                               current_app.config['SECRET_KEY'],
                               algorithms=['HS256'])
            email = email['email']
        except:
            return
        return User.query.filter_by(email=email).first()