class Conversation(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(191)) started_by = db.Column(db.Integer) started_with = db.Column(db.Integer) created_at = db.Column(db.DateTime(), default=datetime.utcnow()) updated_at = db.Column(db.DateTime()) messages = db.relationship('Message', backref='conversation', lazy='dynamic')
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(191), unique=True) password = db.Column(db.String(191)) username = db.Column(db.String(191)) full_name = db.Column(db.String(191)) phone = db.Column(db.String(191)) avatar = db.Column(db.String(191)) socketio_session_id = db.Column(db.String(191)) active = db.Column(db.Boolean(), default=True) created_at = db.Column(db.DateTime(), default=datetime.utcnow()) verified_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) permissions = db.relationship('Permission', secondary=permissions_users, backref=db.backref('users', lazy='dynamic')) def get_password_reset_token(self, expires_sec=1800): s = Serializer(app.config['SECRET_KEY'], expires_sec) return s.dumps({'user_id': self.id}).decode('utf-8') @staticmethod def verify_password_reset_token(token): s = Serializer(app.config['SECRET_KEY']) try: user_id = s.loads(token)['user_id'] except: return None return User.query.get(user_id) def has_role(self, role_name): role = Role.query.filter_by(name=role_name).first() return True if role in self.roles else False def has_permission(self, permission_name): p = Permission.query.filter_by(name=permission_name).first() if p in self.permissions: return True for role in self.roles: if p in role.permissions: return True return False def assign_role(self, role_name): r = Role.query.filter_by(name=role_name).first() self.roles.append(r) def assign_permission(self, permission_name): p = Permission.query.filter_by(name=permission_name).first() self.permissions.append(p)
class Message(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.Text) sent_from = db.Column(db.Integer) sent_to = db.Column(db.Integer) created_at = db.Column(db.DateTime(), default=datetime.utcnow()) conversation_id = db.Column(db.Integer, db.ForeignKey('conversation.id'), nullable=False)
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(191), unique=True) password = db.Column(db.String(191)) username = db.Column(db.String(191)) phone = db.Column(db.String(191)) avatar = db.Column(db.String(191)) created_at = db.Column(db.DateTime(), default=datetime.utcnow()) verified_at = db.Column(db.DateTime()) socketio_session_id = db.Column(db.String(191)) def get_password_reset_token(self, expires_sec=1800): s = Serializer(app.config['SECRET_KEY'], expires_sec) return s.dumps({'user_id': self.id}).decode('utf-8') @staticmethod def verify_password_reset_token(token): s = Serializer(app.config['SECRET_KEY']) try: user_id = s.loads(token)['user_id'] except: return None return User.query.get(user_id)
class User(db.Model): __tablename__ = 'users' user_id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(128), nullable=False) password_hash = db.Column(db.String(128), nullable=False) user_name = db.Column(db.String(32), nullable=False, unique=True) confirmed = db.Column(db.Boolean, default=False) role_id = db.Column(db.Integer, db.ForeignKey("roles.role_id")) # 外键引用 # 额外个人信息 location = db.Column(db.String(64)) about_me = db.Column(db.Text()) register_time = db.Column(db.DateTime(), default=datetime.utcnow) last_login_time = db.Column(db.DateTime(), default=datetime.utcnow) header_picutre = db.Column(db.String(128)) # 博客文章 posts = db.relationship("Post", backref="author", lazy="dynamic") # 关注者(设置lazy=joined是有讲究的, 可以减少反向引用的数据库查询操作) followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') # 我关注的用户 followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') # 关注我的用户 def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) if self.role is None: # 还没关联起来 if self.email == current_app.config["FLASK_ADMIN_USER"]: self.role = Role.query.filter_by(permissions=0xff).first() if self.role is None: # 普通用户或者数据库中并没有管理员的定义, 那么便设置为默认用户 self.role = Role.query.filter_by(default=True).first() @property def password(self): raise AttributeError("password is not a readable attribute") @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def __str__(self): return "<table users %s>" % self.user_id # flask_login 要求的四个函数(或者直接继承UserMixin, 但是这样用户id命名只能是id, 不能死user_id等其他名字) @property def is_active(self): return True @property def is_authenticated(self): return True @property def is_anonymous(self): return False def get_id(self): return unicode(self.user_id) __repr__ = __str__ def generate_confirmation_token(self, expiration=3600): ''' 生成具有过期时间的令牌 @param expiration: ''' serializer = TimedJSONWebSignatureSerializer( current_app.config["SECRET_KEY"], expiration) return serializer.dumps({"confirm": self.user_id }) # 如果user_id自动生成, 那么必须先提交了数据库后才能用这个函数 def confirm(self, token): ''' 注册验证 @param token: ''' serializer = TimedJSONWebSignatureSerializer( current_app.config["SECRET_KEY"]) try: data = serializer.loads(token) except: return False if data.get("confirm") != self.user_id: return False self.confirmed = True db.session.add(self) # 插入会话, 跟随请求结束保存进数据库 return True def ping(self): ''' 刷新用户访问时间 ''' self.last_login_time = datetime.utcnow() db.session.add(self) @staticmethod def generate_fake(count=100): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py seed() for i in range(count): u = User(email=forgery_py.internet.email_address(), user_name=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), confirmed=True, location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), last_login_time=forgery_py.date.date(True)) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback() #==================================================== # 角色权限验证函数(为了保证current_user不需要确保已经登录的前提下就可以使用权限验证函数, 请为匿名用户类也添加一下方法) #==================================================== def can(self, permissions): return self.role is not None and (self.role.permissions & permissions) def is_administrator(self): return self.can(Permission.ADMINISTER) #==================================================== # 用户关注操作 #==================================================== def follow(self, user): ''' 关注操作 @param user: ''' if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): ''' 取消关注操作 @param user: ''' f = self.followed.filter_by(followed_id=user.user_id).first() if f: db.session.delete(f) def is_following(self, user): ''' 是否关注了某个用户 @param user: ''' return self.followed.filter_by( followed_id=user.user_id).first() is not None def is_followed_by(self, user): ''' 是否被某个用户关注 @param user: ''' return self.followers.filter_by( follower_id=user.user_id).first() is not None @property def followed_posts(self): ''' 获取关注的用户的文章 ''' return Post.query.join(Follow, Follow.followed_id == Post.author_id).filter( Follow.follower_id == self.user_id)