class Submit(db.Model): __tablename__ = 'submits' id = db.Column(db.Integer, primary_key=True) status = db.Column(db.String(16), nullable=False) code = db.Column(db.String(100 * 1024), nullable=False) language = db.Column(db.String(16), nullable=False) submitted_on = db.Column(db.DateTime, nullable=False) fk_user = db.Column(db.Integer, db.ForeignKey('users.id'), index=True, nullable=False) user = db.relationship('User', foreign_keys='Submit.fk_user') fk_team = db.Column(db.Integer, db.ForeignKey('teams.id'), index=True, nullable=False) team = db.relationship('Team', foreign_keys='Submit.fk_team') fk_problem = db.Column(db.Integer, db.ForeignKey('problems.id'), index=True, nullable=False) problem = db.relationship('Problem', foreign_keys='Submit.fk_problem')
class Vacancy(db.Model): __tablename__ = 'vacancies' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) short_description = db.Column(db.String(300), nullable=False) text = db.Column(db.Text(), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey('categories.id')) category = db.relationship('Category', backref=db.backref('vacancies')) name_in_url = db.Column(db.String(50), nullable=False, unique=True) visits = db.Column(db.Integer, nullable=False, default=0) salary = db.Column(db.String(50)) description = db.Column(db.String(200)) # for search spider keywords = db.Column(db.String(1000)) city_id = db.Column(db.Integer, db.ForeignKey('cities.id')) city = db.relationship('City', backref=db.backref('vacancies')) is_hidden = db.Column(db.Boolean, nullable=False, default=False) is_deleted = db.Column(db.Boolean, nullable=False, default=False) updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) who_updated = db.relationship('User') condition_is_hidden = ConditionHidden() condition_is_deleted = ConditionDeleted() bl = Resource("bl.vacancy") def __repr__(self): return "[{}] {}".format(self.__class__.__name__, self.title)
class Event(db.Model): __tablename__ = "events" id = db.Column(db.Integer, primary_key=True, autoincrement=True) event_descriptor_id = db.Column(db.Integer, db.ForeignKey('event_descriptors.id'), nullable=False) event_descriptor = db.relationship('EventDescriptor', backref=db.backref('events', lazy='joined')) entity_type = db.Column(db.String(128)) entity_id = db.Column(db.Integer) entity_description = db.Column(db.String(128)) entity_2_type = db.Column(db.String(128)) entity_2_id = db.Column(db.Integer) entity_2_description = db.Column(db.String(128)) entity_3_type = db.Column(db.String(128)) entity_3_id = db.Column(db.Integer) entity_3_description = db.Column(db.String(128)) expiration_date = db.Column(db.DateTime) group_id = db.Column(db.Integer, db.ForeignKey('groups.id')) group = db.relationship('Group', backref=db.backref('events', lazy='joined')) is_processed = db.Column(db.Boolean, default=False, nullable=False) creator_id = db.Column(db.Integer, db.ForeignKey('users.id')) creator = db.relationship('User', backref=db.backref('events', lazy='joined')) created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow) def __init__(self, event_descriptor_id: int): self.event_descriptor_id = event_descriptor_id def push_notification_data(self): event_descriptor = self.event_descriptor message_template = event_descriptor.description if self.entity_description: message_template = message_template.replace( "{1}", self.entity_description) if self.entity_2_description: message_template = message_template.replace( "{2}", self.entity_2_description) if self.entity_3_description: message_template = message_template.replace( "{3}", self.entity_3_description) devices = Device.query_active_devices_for_group( group=self.group, discard_user_ids=[self.creator_id]).all() pn_tokens = [device.pn_token for device in devices] return "Hi", message_template, pn_tokens
class Token(db.Model): __tablename__ = 'tokens' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) user = db.relationship('User', ) token = db.Column(db.String, nullable=False) bl = Resource('bl.token')
class Page(db.Model): __tablename__ = 'pages' # noinspection PyTypeChecker TYPE = IntEnum('Page_type', { 'PROJECTS': 1, 'ABOUT': 2, 'CONTACTS': 3, 'MAINPAGE': 4, }) id = db.Column(db.Integer, primary_key=True) type = db.Column(TypeEnum(TYPE), unique=True, nullable=False) title = db.Column(db.VARCHAR(128)) _blocks = db.relationship( "BlockPageAssociation", order_by='BlockPageAssociation.position', collection_class=ordering_list('position'), cascade='save-update, merge, delete, delete-orphan', ) blocks = association_proxy( '_blocks', 'block', creator=lambda _pb: BlockPageAssociation(block=_pb)) bl = Resource('bl.page') def __str__(self): return '%s (%s)' % (self.title, self.url)
class Contest(db.Model): __tablename__ = 'contests' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), unique=True, nullable=False) rate = db.Column(db.SMALLINT) open_to_public = db.Column(db.Boolean, nullable=False) password = db.Column(db.String(128)) create_dt = db.Column(db.DateTime, nullable=False) start_dt = db.Column(db.DateTime, nullable=False) close_dt = db.Column(db.DateTime) duration = db.Column(db.Time, nullable=False) fk_owner = db.Column(db.Integer, db.ForeignKey('users.id'), index=True, nullable=False) owner = db.relationship('User', foreign_keys='Contest.fk_owner') def hash_password(self, password): password = password.encode('utf-8') self.password = pwd_context.encrypt(password) def verify_password(self, password): password = password.encode('utf-8') return pwd_context.verify(password, self.password)
class TeamMember(db.Model): __tablename__ = 'team_members' fk_user = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True, nullable=False) user = db.relationship('User', foreign_keys='TeamMember.fk_user') fk_team = db.Column(db.Integer, db.ForeignKey('teams.id'), primary_key=True, nullable=False) team = db.relationship('Team', foreign_keys='TeamMember.fk_team') def to_json(self): return dict(user=self.user.to_json(), team=self.team.to_json())
class Device(db.Model): __tablename__ = "devices" id = db.Column(db.Integer, primary_key=True, autoincrement=True) device_id = db.Column(db.String(128), unique=True, nullable=False) device_type = db.Column(db.String(128), nullable=False) active = db.Column(db.Boolean, default=True, nullable=False) pn_token = db.Column(db.String(256), unique=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) user = db.relationship('User', backref=db.backref('devices', lazy='joined')) created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow) def __init__(self, device_id: str, device_type: str, pn_token: str=None, active: bool=True, user=None, created_at: datetime=datetime.utcnow()): self.device_id = device_id self.device_type = device_type # "apple" "android" self.pn_token = pn_token self.active = active self.user = user self.created_at = created_at self.updated_at = created_at # noinspection PyPep8 @staticmethod def query_active_devices_for_user(user: User): return Device.query.filter(Device.user_id == user.id, Device.active == True, Device.pn_token.isnot(None)) # noinspection PyPep8 @staticmethod def query_active_devices_for_group(group: Group, discard_user_ids:List[int]=None): discard_user_ids = discard_user_ids or [] user_ids = [user.user_id for user in group.associated_users if user.user_id not in discard_user_ids] return Device.query.filter(Device.user_id.in_(tuple(user_ids)), Device.active == True, Device.pn_token.isnot(None)) @staticmethod def create_or_update(device_id, device_type: str, user:User=None, active: bool = True, pn_token: str=None): device = Device.first_by(device_id=device_id) if not device: device = Device(device_id=device_id, device_type=device_type, user=user, active=active, pn_token=pn_token) db.session.add(device) else: device.device_type = device_type device.active = active if user: device.user = user if pn_token: device.pn_token = pn_token return device @staticmethod def first_by(**kwargs): """Get first db device that match to device_id""" return Device.query.filter_by(**kwargs).first() @staticmethod def first(*criterion): """Get first db entity that match to criterium""" return Device.query.filter(*criterion)
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) # User Authentication fields username = db.Column(db.String(50), nullable=True, unique=True) # changed nullable to True password = db.Column(db.String(255), nullable=False) # User fields active = db.Column(db.Boolean()) # changed nullable to True first_name = db.Column(db.String(50), nullable=True) # changed nullable to True last_name = db.Column(db.String(50), nullable=True) # Relationship user_emails = db.relationship('UserEmail') roles = db.relationship('Role', secondary='user_roles')
class BlockPageAssociation(db.Model): __tablename__ = 'block_page_associations' page_id = db.Column(db.Integer, db.ForeignKey('pages.id'), primary_key=True) block_id = db.Column(db.Integer, db.ForeignKey('pageblocks.id'), primary_key=True) position = db.Column(db.Integer) block = db.relationship('PageBlock', )
class UserEmail(db.Model): __tablename__ = 'user_emails' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) user = db.relationship('User', uselist=False) # User email information email = db.Column(db.String(255), nullable=False, unique=True) email_confirmed_at = db.Column(db.DateTime()) is_primary = db.Column(db.Boolean(), nullable=False, server_default='0')
class Team(db.Model): __tablename__ = 'teams' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), unique=True, nullable=False) fk_owner = db.Column(db.Integer, db.ForeignKey('users.id'), index=True, nullable=False) owner = db.relationship('User', foreign_keys='Team.fk_owner') def to_json(self): return dict(id=self.id, name=self.name, owner=self.owner.to_json())
class UserGroupAssociation(db.Model): __tablename__ = "user_group_associations" user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) group_id = db.Column(db.Integer, db.ForeignKey('groups.id'), primary_key=True) user = db.relationship("User", back_populates="associated_groups") group = db.relationship("Group", back_populates="associated_users") created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow) def __init__(self, user: User, group: Group): self.user = user self.group = group
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(64), unique = True, index=True) password = db.Column(db.String(128), nullable=False, server_default='') ct = db.Column(db.DateTime()) latest_online = db.Column(db.DateTime()) role_id = db.Column(db.Integer, db.ForeignKey('role.id')) role = db.relationship('Role', back_populates= 'users') # active = db.Column('is_active', db.Boolean(), nullable=False, # server_default='1') sign_in_count = db.Column(db.Integer, nullable=False, default=0) #如果ip不一样,那么这里加1 last_login_time = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(128)) current_login_time = db.Column(db.DateTime()) current_login_ip = db.Column(db.String(128)) @classmethod def encryptpassword(cls, password, salt='$!@>HUI&DWQa`'): import hashlib def sha256(ascii_str): return hashlib.sha256(ascii_str.encode('ascii')).hexdigest() hash1 = sha256(password) hash2 = sha256(hash1 + salt) return hash2 def passwordmatch(self, password=''): return self.password == User.encryptpassword(password) @classmethod def find_by_identity(cls, identity): return User.query.filter(or_(User.username == identity, User.email == identity)).first() def save(self): db.session.add(self) db.session.commit() return None
class Problem(db.Model): __tablename__ = 'problems' id = db.Column(db.Integer, primary_key=True) number = db.Column(db.Integer, nullable=False) rate = db.Column(db.SMALLINT) time_limit = db.Column(db.SMALLINT, nullable=False) ## seconds space_limit = db.Column(db.SMALLINT, nullable=False) ## megabytes body = db.Column(db.String(100 * 1024), nullable=False) fk_contest = db.Column(db.Integer, db.ForeignKey('contests.id'), index=True, nullable=False) contest = db.relationship('Contest', foreign_keys='Problem.fk_contest') __table_args__ = (db.UniqueConstraint('number', 'fk_contest'), )
class Group(db.Model): __tablename__ = "groups" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(128)) associated_users = db.relationship("UserGroupAssociation", back_populates="group") users = association_proxy('associated_users', 'user') created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow) def __init__(self, name: str): self.name = name @staticmethod def get(id: int): """Get db entity that match the id""" return Group.query.get(id)
class MailTemplate(db.Model): __tablename__ = 'mailtemplates' # noinspection PyTypeChecker MAIL = IntEnum('Mail', { 'CV': 0, 'REPLY': 1, }) id = db.Column(db.Integer, primary_key=True) mail = db.Column(TypeEnum(MAIL), nullable=False) title = db.Column(db.String, nullable=False) subject = db.Column(db.String(79), nullable=False) html = db.Column(db.Text, nullable=False) help_msg = db.Column(db.Text) updated_at = db.Column(db.Date, onupdate=datetime.datetime.now, default=datetime.datetime.now) bl = Resource('bl.mailtemplate') user_id = db.Column(db.Integer, db.ForeignKey('users.id')) who_updated = db.relationship('User') def __repr__(self): return str(self.title)
class User(db.Model): __tablename__ = 'users' ID = db.Column(db.Integer, primary_key=True, nullable=False) nome = db.Column(db.Text(100), unique=False, nullable=False) email = db.Column(db.Text(100), unique=True, nullable=False) senha = db.Column(db.Text, nullable=False) roles = db.Column(db.Text) is_active = db.Column(db.Boolean, default=True, server_default="true") receitas = db.relationship('Recipe', backref='users', lazy=True) @property def identity(self): """ *Required Attribute or Property* flask-praetorian requires that the user class has an ``identity`` instance attribute or property that provides the unique id of the user instance """ return self.ID @property def rolenames(self): """ *Required Attribute or Property* flask-praetorian requires that the user class has a ``rolenames`` instance attribute or property that provides a list of strings that describe the roles attached to the user instance """ try: return self.roles.split(",") except Exception: return [] @property def password(self): """ *Required Attribute or Property* flask-praetorian requires that the user class has a ``password`` instance attribute or property that provides the hashed password assigned to the user instance """ return self.senha @classmethod def lookup(cls, username): """ *Required Method* flask-praetorian requires that the user class implements a ``lookup()`` class method that takes a single ``username`` argument and returns a user instance if there is one that matches or ``None`` if there is not. """ return User.query.filter_by(email=username).one_or_none() @classmethod def identify(cls, id): """ *Required Method* flask-praetorian requires that the user class implements an ``identify()`` class method that takes a single ``id`` argument and returns user instance if there is one that matches or ``None`` if there is not. """ return User.query.get(id) def is_valid(self): return self.is_active def as_dict( self ): # Não usa a senha no dic, uma vez que ela está em bytes e não é serializável return {'UserID': self.ID, 'nome': self.nome, 'email': self.email}
class Role(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(64), index= True) users = db.relationship('User', back_populates= 'role')