class Role(SurrogatePK, Model, RoleMixin): """A role for a user.""" __tablename__ = 'roles' name = db.Column(db.String(80)) parents = db.relationship( 'Role', secondary=roles_parents, primaryjoin=("Role.id == roles_parents.c.role_id"), secondaryjoin=("Role.id == roles_parents.c.parent_id"), backref=db.backref('children', lazy='dynamic')) def __init__(self, name): RoleMixin.__init__(self) self.name = name def add_parent(self, parent): # You don't need to add this role to parent's children set, # relationship between roles would do this work automatically self.parents.append(parent) def add_parents(self, *parents): for parent in parents: self.add_parent(parent) @staticmethod def get_by_name(name): return Role.query.filter_by(name=name).first()
class UserMarkType(SurrogatePK,Model): __tablename__ = 'user_mark_types' name = Column(db.String(80)) user_mark = db.relationship('UserMark', backref='user_marks',uselist=False) user = reference_col('users')
class ContentAttr(SurrogatePK, Model): """内容属性, 默认的三个类型选项,mark标记唯一 用户无法更改 数据库 读取mark标记 #普通common 首页home 热门hot 推荐recd """ __tablename__ = 'content_attrs' name = Column(db.String(80), nullable=False) mark = Column(db.String(80),unique=True,nullable=False) #文章 article = db.relationship('Article', backref='content_attrs',lazy='dynamic') #图集 photo = db.relationship('Photo', backref='content_attrs',lazy='dynamic') def __repr__(self): return '<ArticeAttr({name!r})>'.format(name=self.name)
class Articles(CRUDMixin, db.Model): __tablename__ = 'article_model' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, name="Название", nullable=False) url = db.Column(db.String, name="Url", nullable=False) anons = db.Column(db.Text, name="Анонс") date = db.Column(db.DateTime, default=datetime.datetime.now) tags = db.relationship(Tag, secondary=article_tags_meta) author = db.Column(db.String, name="Автор") text = db.Column(db.Text, name="Результат") image = db.Column(db.String, nullable=False)
class ItemModel(BaseModel): """Model for Item""" __tablename__ = 'item' name = Column(String(64), nullable=False) description = Column(String(255)) # Define foreign keys category_id = Column(Integer, ForeignKey('category.id')) user_id = Column(Integer, ForeignKey('user.id')) # Define relationships category = db.relationship('CategoryModel', back_populates='items', lazy=True) user = db.relationship('UserModel', back_populates='items', lazy=True) # Additional fields is_owner = None def __init__(self, **kwargs): self.__dict__.update(kwargs) # If during object creation, description is null then init an empty string for it self.description = kwargs.get('description') if kwargs.get('description') is not None else ''
class CategoryModel(BaseModel): """Model for Category""" __tablename__ = 'category' name = Column(String(64), nullable=False, unique=True) description = Column(String(255)) # Define relationships items = db.relationship('ItemModel', back_populates='category', lazy='dynamic') @classmethod def get_all(cls): """Get all records of categories from the database. :return: A list of Category existing in the database """ return cls.query.all()
class UserModel(BaseModel): """Model for User""" __tablename__ = 'user' username = Column(String(30), unique=True, nullable=False) email = Column(String(255), unique=True, nullable=False) name = Column(String(64), nullable=False) encrypted_password = Column(String(64), nullable=False) # Define relationships items = db.relationship('ItemModel', back_populates='user', lazy='dynamic') # None-sql fields password = None def __init__(self, username, email, name, encrypted_password): self.username = username self.email = email self.name = name self.encrypted_password = encrypted_password @classmethod def find_user_by_username_or_email(cls, username='', email=''): """Find user by username and verify its password. :param username: Username of the user :param email: Email of the user :return: User instance corresponds to the user, or None """ user = cls.query.filter( or_(cls.username == username, cls.email == email)).first() if user: return user else: return None
class Photo(SurrogatePK,Model): __tablename__ = 'photos' #:图集标题 title = Column(db.String(80),nullable=False) #:图集描述 summary = Column(db.String(500)) #:关键字 key = Column(db.String(80)) #:关键描述 word = Column(db.String(500)) #:拍摄时间 photos_date = Column(db.DateTime(),default=dt.datetime.now) #:创建时间 creation_date = Column(db.DateTime(),default=dt.datetime.now) #缩略图 #保存路径 image = Column(db.String(200)) image_alt = Column(db.String(80)) #:浏览次数 count = Column(db.Integer,default=100) #:是否显示 is_enable = Column(db.Boolean,default=True) #图集属性 attr_id = db.Column(db.Integer,db.ForeignKey('content_attrs.id')) #图集照片 photo_image = db.relationship('PhotoImage', backref='photo_images',lazy='dynamic') #附加字段,附加字段值 attach_key = Column(db.String(200)) attach_value = Column(db.String(500)) #静态内容,用“|”号隔开 static_context = Column(db.UnicodeText) user = reference_col('users') category = reference_col('categorys')
class User(SurrogatePK, Model, UserMixin): """用户表. 表名称:users 列名称: - username:用户名 - password:密码 ,hashed password - created_at:创建时间 - name:姓名 - active:是否激活。默认false - active_at:激活时间,默认当前时间 - is_admin:是否管理员 - is_center:是否报单中心 - phone:手机号,用于登录等 - buys_id:外键引用 产品购买表 - integral:积分 - coins:硬币 - parent_center:引用自身 上级 - children_center:引用自身 - recommends:引用推荐表 - recommender:外键引用推荐人表 - buys_car_id:外键购物车 """ __tablename__ = 'users' username = Column(db.String(80), unique=True, nullable=False) password = Column(db.Binary(128), nullable=False) created_at = Column(db.DateTime, nullable=False, default=datetime.datetime.now) name = Column(db.String(30)) active = Column(db.Boolean(), default=False) active_at = Column(db.DateTime, nullable=False, default=datetime.datetime.now) is_admin = Column(db.Boolean(), default=False) is_center = Column(db.Boolean(), default=False) phone = Column(db.String(30), unique=True) integral = Column(db.Integer(), default=0) coins = Column(db.Integer(), default=0) parent_center = reference_col('users') buys_id = relationship('Order', backref='user') children_center = relationship("User", join_depth=2, lazy="joined", post_update=True) recommends = db.relationship('Recommend', foreign_keys=[Recommend.recommender_id], backref=db.backref('recommender', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') recommender = db.relationship('Recommend', foreign_keys=[Recommend.recommends_id], backref=db.backref('recommends', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') buys_car_id = relationship(BuysCar, backref='users') roles = db.relationship('Role', secondary=users_roles, backref=db.backref('roles', lazy='dynamic')) def __init__(self, username, password=None, **kwargs): """Create instance.""" db.Model.__init__(self, username=username, **kwargs) if password: self.set_password(password) else: self.password = None def set_password(self, password): """Set password.""" self.password = bcrypt.generate_password_hash(password) def check_password(self, value): """Check password.""" return bcrypt.check_password_hash(self.password, value) @property def full_name(self): """Full user name.""" return '{0} {1}'.format(self.first_name, self.last_name) def __repr__(self): """Represent instance as a unique string.""" return '<User({username!r})>'.format(username=self.username) def is_administrator(self): """管理员""" return self.is_admin def init_insert(): User.create(username='******', password='******', active=True) def generate_auth_token(self, expiration=600): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}) @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token user = User.query.get(data['id']) return user def add_role(self, role): self.roles.append(role) def add_roles(self, roles): for role in roles: self.add_role(role) def get_roles(self): for role in self.roles: yield role