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 Movie(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) rating = db.Column(db.Float, nullable=False, default=0) image = db.Column(db.String(90), nullable=False, default='default_img.png') like = db.relationship('User', secondary=likes, backref=db.backref('like', lazy='dynamic')) Genre = db.Column(db.String(100)) Action = db.Column(db.Integer, nullable=False) Adventure = db.Column(db.Integer, nullable=False) Animation = db.Column(db.Integer, nullable=False) Comedy = db.Column(db.Integer, nullable=False) Crime = db.Column(db.Integer, nullable=False) Documentary = db.Column(db.Integer, nullable=False) Drama = db.Column(db.Integer, nullable=False) Family = db.Column(db.Integer, nullable=False) Fantasy = db.Column(db.Integer, nullable=False) Foreign = db.Column(db.Integer, nullable=False) History = db.Column(db.Integer, nullable=False) Horror = db.Column(db.Integer, nullable=False) Music = db.Column(db.Integer, nullable=False) Mystery = db.Column(db.Integer, nullable=False) Romance = db.Column(db.Integer, nullable=False) Science_Fiction = db.Column(db.Integer, nullable=False) Tv_Movie = db.Column(db.Integer, nullable=False) Thriller = db.Column(db.Integer, nullable=False) War = db.Column(db.Integer, nullable=False) Western = db.Column(db.Integer, nullable=False) def __repr__(self): return f"Movie:{self.name},rating:{self.rating}"
class Role(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) permissions = db.relationship('Permission', secondary=permissions_roles, backref=db.backref('roles', lazy='dynamic')) def has_permission(self, permission_name): p = Permission.query.filter_by(name=permission_name).first() return True if p in self.permissions else False def assign_permission(self, permission_name): p = Permission.query.filter_by(name=permission_name).first() self.roles.append(p)
class User(UserMixin, db.Model): #General Info 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) avatar = db.Column(db.String(100)) password_hash = db.Column(db.String(128)) #Post Relationship posts = db.relationship('Post', backref='author', lazy='dynamic') #Follower Relationship 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 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()) #General info about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow) def __repr__(self): return '<User {}>'.format(self.username) #Set and check password 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)
class User(db.Model, UserMixin): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(11), nullable=False, unique=True) password = db.Column(db.String(128), nullable=False) active = db.Column(db.Boolean(), default=True, nullable=False) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) services = db.relationship('Service', secondary=services_users, backref=db.backref('users', lazy='dynamic')) def __init__(self, username=None, password=None, active=True): self.username = username self.password = bcrypt.encrypt(password) self.active = True @staticmethod def authenticate(username, password): user = User.query.filter(User.username == username).one() if user and bcrypt.verify(password, user.password): return user
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 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 __repr__(self): return '<User {}>'.format(self.username) 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())
class productos(db.Model): __tablename__ = 'Productos' Codigo = db.Column(db.Integer, primary_key=True) nombre = db.Column(db.String(50), nullable=False) PrecioCompra = db.Column(db.Numeric) PrecioVenta = db.Column(db.Numeric) stock = db.Column(db.Numeric) Categoria = db.Column(db.Integer, db.ForeignKey("categoria.id"), nullable=False) #relacion categori = db.relationship('Categoria', backref=db.backref('Productos', lazy=True)) def __relp__(self): return '{0}'.format(self.Codigo)
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)
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)