class Admin(db.Model, UserMixin): """Admin model for the admins. The admin model is extended by the UserMixin model supplied by the Flask-Login package. The UserMixin model contains several commonly used fields like is_authenticated, is_annonymous, and others which are commonly needed for authenticating a user. The application requires atleast one superadmin throughout its life- cycle as only they can create or remove other admins. Default value of is_superadmin is false. An Admin is related to two other models so far. First one is to a Staff through one-to-many relationship. An Admin can create many staffs. Another is to the GithubAccessHistory, also through a one- to-many relationship. An Admin can invoke or revoke permissions of many Staffs many times. Any history of invoking or revoking github permissions on any staff by the Admin can be accessed through github_actions field. """ __tablename__ = 'admins' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(128), nullable=False, unique=True) password = db.Column(db.String(128), nullable=False) is_superadmin = db.Column(db.Boolean(), default=True, nullable=False) added_staffs = db.relationship('Staff', backref='added_by') github_actions = db.relationship('GithubAccessHistory', backref='action_by') def __init__(self, email, password, is_super=False): self.email = email self.password = password self.is_superadmin = is_super
class GithubAccessHistory(db.Model): """History of Github access permission by Admins on Staffs. Contains all the detailed invoked or revoked histories of github permission on staffs. The action field will contain any comments about the action such as invoked permission, revoked permission, cancelled pending, etc. This model is backreferenced by Admin through action_by field, and Staff through action_on field. Therefore, the Admin and the Staff related to a particular history should be supplied to the initializer through the respected arguments. admin_id and staff_id will then automatically contain the ids of respective models related to the particular history. """ __tablename__ = 'githubaccesshistory' id = db.Column(db.Integer, primary_key=True) action = db.Column(db.String(128), nullable=False) datetime = db.Column(db.DateTime, nullable=False) admin_id = db.Column(db.Integer, db.ForeignKey('admins.id')) staff_id = db.Column(db.Integer, db.ForeignKey('staffs.id')) def __init__(self, action, datetime, action_by, action_on): self.action = action self.datetime = datetime self.action_by = action_by self.action_on = action_on
class Staff(db.Model): """Staff model for the staffs. Staff is a simple model for the staffs, where each staff is identified by his email. It contains a github_status field which contains the current access status of the staff to the organization's github repositories. This field can contain one of the following values: 1. 'uninvited': the staff has not been invited yet 2. 'pending': the staff is invited but not accepted invitation 3. 'granted': the staff has access to the github repos This model is backreferenced by an Admin who created the Staff. During initialization, it is required to pass the Admin through added_by parameter. Any history of invoked or revoked permissions on this Staff can be accessed through github_actions field. """ __tablename__ = 'staffs' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(128), nullable=False, unique=True) github_status = db.Column(db.String(128), nullable=False) admin_id = db.Column(db.Integer, db.ForeignKey('admins.id')) github_actions = db.relationship('GithubAccessHistory', backref='action_on') def __init__(self, email, added_by, github_status='uninvited'): self.email = email self.github_status = github_status self.added_by = added_by
class GatewayModel(CRUDMixin, HelperMixin, db.Model): __tablename__ = 'gateway_model' id = db.Column(db.Integer, primary_key=True) gateway_id = db.Column(db.Integer, db.ForeignKey('gateway.id', ondelete='CASCADE', onupdate='CASCADE'), unique=True, index=True, nullable=False) model_id = db.Column(db.Integer, db.ForeignKey('data_model.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) created_at = db.Column(db.DateTime, default=utils.get_utc_now) gateway = db.relationship('Gateway', backref=db.backref('gateway_model', lazy='joined'), lazy='joined') data_model = db.relationship('DataModel', backref=db.backref('gateway_model', lazy='joined'), lazy='joined') def __init__(self, gateway_id=None, model_id=None): self.gateway_id = gateway_id self.model_id = model_id def __repr__(self): return "<GatewayModel(id='%s',gateway_id='%s',model_id='%s',created_at='%s')>" % ( str(self.id), str(self.gateway_id), str( self.model_id), str(self.created_at))
class Blog(db.Model): __tablename__ = 'blog' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(64), unique=True) content = db.Column(db.Text, ) author_id = db.Column(db.Integer, db.ForeignKey('user.id'), comment=u'作者') def __repr__(self): return self.title
class Tree(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) # recursive relationship parent_id = db.Column(db.Integer, db.ForeignKey('tree.id')) parent = db.relationship('Tree', remote_side=[id], backref='children') def __str__(self): return "{}".format(self.name)
class DataSet(CRUDMixin, HelperMixin, db.Model): __tablename__ = 'dataset' id = db.Column(db.Integer, primary_key=True) filename = db.Column(db.VARCHAR(255)) dataformat = db.Column(db.VARCHAR(10)) title = db.Column(db.VARCHAR(50)) rows = db.Column(db.Integer) columns = db.Column(db.Integer) description = db.Column(db.VARCHAR(200)) uploadtime = db.Column(db.DateTime) status = db.Column(db.VARCHAR(10)) def __init__(self, filename=None, dataformat=None, title=None, rows=None, columns=None, description=None, uploadtime=None, status=None): self.filename = filename self.dataformat = dataformat self.title = title self.rows = rows self.columns = columns self.description = description self.uploadtime = uploadtime self.status = status def __repr__(self): return "<DataSet(id='%s',filename='%s',dataformat='%s',title='%s',rows='%s',columns='%s',description='%s'," \ "uploadtime='%s')>" % (str(self.id), self.filename, self.dataformat, self.title, str(self.rows), str(self.columns), self.description, str(self.uploadtime), self.status)
class ActualWeather(CRUDMixin,HelperMixin,db.Model): __tablename__='actual_weather' id = db.Column(db.Integer,primary_key=True) publish_date = db.Column(db.DATE) created_at = db.Column(db.VARCHAR(100)) region_id = db.Column(db.Integer,db.ForeignKey('region.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) forecast_data = db.Column(db.DATE) order = db.Column(db.Integer) temperature = db.Column(db.FLOAT) humidity = db.Column(db.FLOAT) weather=db.Column(db.VARCHAR(45)) def __init__(self,publish_date=None,created_at=None,region_id=None,forecast_data=None,order=None,temperature=None,humidity=None,weather=None): self.publish_date = publish_date self.created_at = created_at self.region_id = region_id self.forecast_data = forecast_data self.order = order self.temperature = temperature self.humidity = humidity self.weather = weather def __repr__(self): return "<ActualWeather(id='%s',publish_date='%s',created_at='%s',region_id='%s',forecast_data='%s',order='%s',temperature='%s',humidity='%s',weather='%s')>" % ( str(self.id),str(publish_date),str(created_at),str(self.region_id),str(self.forecast_data),str(self.order),str(self.temperature),str(self.humidity),self.weather)
class Role(db.Model): __tablename__ = 'role' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), unique=True, nullable=False) status = db.Column(db.Integer, default=1, nullable=False) # 是否有效 0 无效 1有效 def __repr__(self): return self.name def __str__(self): return self.name
class Test(CRUDMixin, HelperMixin,db.Model): __tablename__='test' id = db.Column(db.Integer,primary_key=True) name = db.Column(db.VARCHAR(20)) age = db.Column(db.VARCHAR(20)) def __init__(self,name=None ,age=None): self.name = name self.age = age def __repr__(self): return "<Test(id='%s',name='%s',age='%s')>" % (str(self.id),self.name,self.age)
class Gateway(CRUDMixin, HelperMixin, db.Model): __tablename__ = 'gateway' __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.VARCHAR(30)) url = db.Column(db.VARCHAR(30)) address = db.Column(db.VARCHAR(50)) latitude = db.Column(db.VARCHAR(20)) longitude = db.Column(db.VARCHAR(20)) status = db.Column(db.Boolean) created_at = db.Column(db.DateTime, default=utils.get_utc_now) def __init__(self, name=None, url=None, address=None, latitude=None, longitude=None, status=False): self.name = name self.url = url self.address = address self.latitude = latitude self.longitude = longitude self.status = status def __repr__(self): return "<Gateway(id='%s',name='%s',url='%s',address='%s',latitude='%s', longitude='%s', created_at='%s')>" % ( str(self.id), self.name, self.url, self.address, self.latitude, self.longitude, str(self.created_at))
class DataModel(CRUDMixin,HelperMixin,db.Model): __tablename__='data_model' id = db.Column(db.Integer,primary_key=True) dataset_id = db.Column(db.Integer, db.ForeignKey('dataset.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) name = db.Column(db.VARCHAR(100)) algorithm_type = db.Column(db.VARCHAR(50)) serialization = db.Column(db.Integer) description = db.Column(db.VARCHAR(200)) created_at = db.Column(db.DateTime) status = db.Column(db.VARCHAR(1)) dataset = db.relationship('DataSet', backref=db.backref('data_model', lazy='joined'), lazy='joined') def __init__(self,dataset_id=None,name=None,algorithm_type=None,serialization=None,description=None,created_at=None,status=None): self.dataset_id = dataset_id self.name = name self.algorithm_type = algorithm_type self.serialization = serialization self.description = description self.created_at = created_at self.status = status def __repr__(self): return "<DataModel(id='%s',dataset_id='%s',name='%s',algorithm_type='%s',serialization='%s',description='%s',created_at='%s',status='%s')>" % ( str(self.id),str(dataset_id),self.name,self.algorithm_type,self.serialization,self.description,str(self.created_at),str(self.status))
class Resume(db.Model): id = db.Column(db.Integer, primary_key=True) main_flag = db.Column(db.Boolean, nullable=False) mongo_key = db.Column(db.String(100), nullable=False) user_id = db.Column(db.String(32), db.ForeignKey('user.id')) @property def get_data(self): dictionary = self.__dict__ try: del dictionary['_sa_instance_state'] dictionary['user_id'] = self.user_id.hex except: pass return dictionary
class TokenMapping(db.Model): __tablename__ = "user_token_mapping" id = db.Column(db.Integer, primary_key=True, nullable=False, unique=True, autoincrement=True) uuid = db.Column(db.String(40), nullable=False) token = db.Column(db.String(250), nullable=False) created = db.Column(db.DateTime, nullable=False, default=datetime.now) modified = db.Column(db.DateTime, nullable=False, default=datetime.now) def __init__(self, uuid, token): self.uuid = uuid self.token = token
class Role(db.Model): __tablename__ = 'user_role' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(15), nullable=False) cname = db.Column(db.String(30)) def __init__(self, role_id, name, cname=None): self.id = role_id self.name = name self.cname = cname @staticmethod def _get_name(role_id): role = db.session.query(Role).filter(Role.id == role_id).first() return role.cname
class ActualPower(CRUDMixin,HelperMixin,db.Model): __tablename__='actual_power' id = db.Column(db.Integer,primary_key=True) collect_data = db.Column(db.DATE) region_id = db.Column(db.Integer,db.ForeignKey('region.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) power=db.Column(db.FLOAT) def __init__(self,collect_data=None,region_id=None,power=None): self.collect_data = collect_data self.region_id = region_id self.power = power def __repr__(self): return "<ActualPower(id='%s',collect_data='%s',region_id='%s',power='%s')>" % ( str(self.id),str(created_at),str(self.region_id),str(self.power))
class JobSector(db.Model): __tablename__ = "jobsector" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(200)) skills = db.relationship('JobSkill', secondary=skills_sector_table) def __str__(self): return "{}".format(self.name) @property def get_data(self): dictionary = self.__dict__ try: del dictionary['_sa_instance_state'] except: pass return dictionary
class HisWeather(CRUDMixin, HelperMixin, db.Model): __tablename__ = 'his_weather' id = db.Column(db.Integer, primary_key=True) publish_date = db.Column(db.DATE) created_at = db.Column(db.DateTime, default=utils.get_utc_now) region_id = db.Column(db.Integer, db.ForeignKey('gateway.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) temperature = db.Column(db.FLOAT) humidity = db.Column(db.FLOAT) weather = db.Column(db.VARCHAR(45)) def __init__(self, publish_date=None, region_id=None, temperature=None, humidity=None, weather=None): self.publish_date = publish_date # self.created_at = created_at self.region_id = region_id self.temperature = temperature self.humidity = humidity self.weather = weather def __repr__(self): return "<HisWeather(id='%s',publish_date='%s',created_at='%s',region_id='%s',temperature='%s',humidity='%s'," \ "weather='%s')>" % (str(self.id), str(self.publish_date), str(self.created_at), str(self.region_id), str(self.temperature), str(self.humidity), self.weather)
class PredictedPower(CRUDMixin, HelperMixin, db.Model): __tablename__ = 'predicted_power' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=utils.get_utc_now) region_id = db.Column(db.Integer, db.ForeignKey('gateway.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) predict_date = db.Column(db.DATE) publish_date = db.Column(db.DATE) order = db.Column(db.Integer) power = db.Column(db.FLOAT) def __init__(self, region_id=None, predict_date=None, publish_date=None, order=None, power=None): self.publish_date = publish_date self.region_id = region_id self.predict_date = predict_date self.order = order self.power = power def __repr__(self): return "<PredictedPower(id='%s',created_at='%s',region_id='%s',predict_date='%s',order='%s',power='%s')>" % \ (str(self.id), str(self.created_at), str(self.region_id), str(self.predict_date), str(self.order), str(self.power))
class User(CRUDMixin, HelperMixin, db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.VARCHAR(20)) password = db.Column(db.VARCHAR(64)) phone = db.Column(db.VARCHAR(15)) gateway_id = db.Column(db.Integer, db.ForeignKey('gateway.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) gateway = db.relation('Gateway', backref='user', lazy=False) created_at = db.Column(db.DateTime, default=utils.get_utc_now) def __init__(self, username=None, password=None, gateway_id=None, phone=None): self.username = username self.password = password self.gateway_id = gateway_id self.phone = phone def __repr__(self): return "<User(id='%s',username='******',password='******',gateway_id='%s',created_at='%s')>" % ( str(self.id), self.username, self.password, self.gateway_id, str(self.created_at))
class User(db.Model, UserMixin): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), unique=True, nullable=False) email = db.Column(db.String(128), unique=True, nullable=False) password = db.Column(db.String(128), nullable=False) is_admin = db.Column(db.Integer, default=0, nullable=False) # 是否管理员 0 不是 1 是 status = db.Column(db.Integer, default=1, nullable=False) # 是否有效 0 无效 1有效 roles = db.relationship( "Role", secondary=user_role, lazy='subquery', backref=db.backref('users', lazy=True), ) # 功能模块-用户关联部分 # 定义一对多关系 # blogs: 一个用户有多个博客,字段:复数 # author:一篇博客只能属于一个用户,字段:单数 blogs = db.relationship( 'Blog', backref='author', ) def __repr__(self): return self.username
class Operation(db.Model): """ 可以把此看作权限表,但我将其定义为 操作某种资源(资源的定义参考 restfull api设计理念)的一系列动作, 如 查看 某个 资源, 如 新增 一个资源 而把 某动作 授予 某个角色,即完成了权限的管理(绑定) """ __tablename__ = 'operation' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) method = db.Column(db.String(32), default='GET', ) uri = db.Column(db.String(256), default='/', nullable=False) roles = db.relationship( "Role", secondary=role_operation, lazy='subquery', backref=db.backref('operations', lazy=True), ) description = db.Column(db.Text, comment=u'描述信息') def __repr__(self): return self.name
class Group(db.Model): __tablename__ = 'user_group' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(50), nullable=False) cname = db.Column(db.String(100)) selectors = db.Column(db.Text) def __init__(self, name, cname=None, selectors=None): self.name = name self.cname = cname self.selectors = selectors def _to_dict(self): return { col.name: getattr(self, col.name, None) for col in self.__table__.columns } @staticmethod def _from_dict(group_dict): return Group(name=group_dict.get('name'), cname=group_dict.get('cname'), selectors=group_dict.get('selectors'))
class Selector(db.Model): __tablename__ = 'user_selector' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(50), nullable=False) cname = db.Column(db.String(50)) kind = db.Column(db.String(50)) def __init__(self, name, cname, kind): self.name = name self.cname = cname self.kind = kind def _to_dict(self): return { col.name: getattr(self, col.name, None) for col in self.__table__.columns } @staticmethod def _from_dict(selector_dict): return Selector(name=selector_dict.get('name'), cname=selector_dict.get('cname'), kind=selector_dict.get('kind'))
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(120)) text = db.Column(db.Text, nullable=False) date = db.Column(db.Date) # some sqlalchemy_utils data types (see https://sqlalchemy-utils.readthedocs.io/) background_color = db.Column(ColorType) created_at = db.Column(ArrowType, default=arrow.utcnow()) user_id = db.Column(UUIDType(binary=False), db.ForeignKey(User.id)) user = db.relationship(User, foreign_keys=[user_id], backref='posts') tags = db.relationship('Tag', secondary=post_tags_table) def __str__(self): return "{}".format(self.title)
class User(db.Model): id = db.Column(UUIDType(binary=False), default=uuid.uuid4, primary_key=True) password = db.Column(db.String(128)) auth = db.Column(db.String(100)) email = db.Column(EmailType, unique=True, nullable=False) nickname = db.Column(db.String(100), nullable=False) thumbnail = db.Column(URLType, default='/static/img/wdticon.png') create_date = db.Column(db.DateTime) resume = db.relationship('Resume') @property def is_authenticated(self): return True @property def is_admin(self): if self.auth == u'admin': return True else: return False @property def is_active(self): return True @property def is_anonymous(self): return False def get_id(self): return self.id # Required for administrative interface def __unicode__(self): return self.username
class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Unicode(64), unique=True) def __str__(self): return "{}".format(self.name)
class User(db.Model): id = db.Column(UUIDType(binary=False), default=uuid.uuid4, primary_key=True) # use a regular string field, for which we can specify a list of available choices later on type = db.Column(db.String(100)) # fixed choices can be handled in a number of different ways: enum_choice_field = db.Column(db.Enum(EnumChoices), nullable=True) sqla_utils_choice_field = db.Column(ChoiceType(AVAILABLE_USER_TYPES), nullable=True) sqla_utils_enum_choice_field = db.Column(ChoiceType(EnumChoices, impl=db.Integer()), nullable=True) first_name = db.Column(db.String(100)) last_name = db.Column(db.String(100)) # some sqlalchemy_utils data types (see https://sqlalchemy-utils.readthedocs.io/) email = db.Column(EmailType, unique=True, nullable=False) website = db.Column(URLType) ip_address = db.Column(IPAddressType) currency = db.Column(CurrencyType, nullable=True, default=None) timezone = db.Column(TimezoneType(backend='pytz')) dialling_code = db.Column(db.Integer()) local_phone_number = db.Column(db.String(10)) featured_post_id = db.Column(db.Integer, db.ForeignKey('post.id')) featured_post = db.relationship('Post', foreign_keys=[featured_post_id]) @hybrid_property def phone_number(self): if self.dialling_code and self.local_phone_number: number = str(self.local_phone_number) return "+{} ({}) {} {} {}".format(self.dialling_code, number[0], number[1:3], number[3:6], number[6::]) return @phone_number.expression def phone_number(cls): return sql.operators.ColumnOperators.concat(cast(cls.dialling_code, db.String), cls.local_phone_number) def __str__(self): return "{}, {}".format(self.last_name, self.first_name) def __repr__(self): return "{}: {}".format(self.id, self.__str__())
@phone_number.expression def phone_number(cls): return sql.operators.ColumnOperators.concat(cast(cls.dialling_code, db.String), cls.local_phone_number) def __str__(self): return "{}, {}".format(self.last_name, self.first_name) def __repr__(self): return "{}: {}".format(self.id, self.__str__()) #---<Create M2M table>---# post_tags_table = db.Table('post_tags', db.Model.metadata, db.Column('post_id', db.Integer, db.ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')) ) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(120)) text = db.Column(db.Text, nullable=False) date = db.Column(db.Date) # some sqlalchemy_utils data types (see https://sqlalchemy-utils.readthedocs.io/) background_color = db.Column(ColorType) created_at = db.Column(ArrowType, default=arrow.utcnow()) user_id = db.Column(UUIDType(binary=False), db.ForeignKey(User.id))
#! coding: utf8 from admin import db from flask_login import UserMixin user_role = db.Table( 'user_role', db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True), db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True), ) class User(db.Model, UserMixin): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), unique=True, nullable=False) email = db.Column(db.String(128), unique=True, nullable=False) password = db.Column(db.String(128), nullable=False) is_admin = db.Column(db.Integer, default=0, nullable=False) # 是否管理员 0 不是 1 是 status = db.Column(db.Integer, default=1, nullable=False) # 是否有效 0 无效 1有效 roles = db.relationship( "Role", secondary=user_role, lazy='subquery', backref=db.backref('users', lazy=True), ) # 功能模块-用户关联部分 # 定义一对多关系