class Session(Model): __tablename__ = 'sessions' id = Column(db.Integer, primary_key=True) user_id = Column(db.Integer, db.ForeignKey('users.id')) timestamp = Column(db.DateTime, default=datetime.utcnow) type = Column(db.String(32)) routes = relationship('Route', backref='session', lazy='dynamic')
class Task(Model): __tablename__ = 'tasks' id = db.Column(db.String(36), primary_key=True) # pylint: disable=invalid-name name = Column(db.String(128), index=True) description = Column(db.String(128)) user_id = Column(db.Integer, db.ForeignKey('users.id')) complete = Column(db.Boolean, default=False) def __init__(self, id: str, name: str, description: str, user: '******') -> None: db.Model.__init__(self, id=id, name=name, description=description, user=user) def get_rq_job(self): try: rq_job = rq.job.Job.fetch(self.id, connection=current_app.redis) except (RedisError, NoSuchJobError): return None return rq_job def get_progress(self): job = self.get_rq_job() return job.meta.get('progress', 0) if job is not None else 100
class State(Model): __tablename__ = 'states' id = Column(db.Integer, primary_key=True) abv = Column(db.String()) name = Column(db.String()) color = Column(db.String()) records = relationship('Record', backref='state', lazy='dynamic')
class Role(Model): __tablename__ = 'roles' id = Column(db.Integer, primary_key=True) name = Column(db.String(64), unique=True) users = relationship('User', backref='role', lazy='dynamic') def __repr__(self): return f'<Role {self.name}, {self.id}>'
class Team(PkModel): """A role for a user.""" __tablename__ = "team" id = Column(db.Integer, primary_key=True) name = Column(db.String(80)) players = relationship("Player", backref="team", lazy=True) division = Column(db.Integer) matches = relationship("Match", backref="team", lazy=True) player_stats = relationship("PlayerStat", backref="team", lazy=True) event_id = db.Column(db.Integer, db.ForeignKey('event.id'), nullable=False) def __init__(self, name, **kwargs): """Create instance.""" super().__init__(**kwargs) def __repr__(self): return "Team {}, {} Rating".format(self.name, self.rating) async def refresh_stats(self, startTimestamp=None, endTimestamp=None): all_matches = await get_matches_for_team(self, startTimestamp=startTimestamp, endTimestamp=endTimestamp) for match in all_matches: player_stats = [] match_data = json.dumps(match) match_data = json.loads(match_data) for stat in match_data['stats']: player_stat = PlayerStat(stat['player']['uno'], stat['playerStats']['kills'], stat['playerStats']['teamPlacement']) player_stats.append(player_stat) match = Match(match_data['id'], player_stats) self.add_match(match) #for stat in stats: # player_kills = stat['playerStats']['kills'] # team_placement = stat['playerStats']['teamPlacement'] #asyncio.get_event_loop().run_until_complete(get_team_matches(self)) #asyncio.run(get_team_matches(self)) def add_match(self, match): if self.matches is None: self.matches = [] if match.external_id in [match.external_id for match in self.matches]: return self.matches.append(match) print("added match {}".format(match.external_id)) @property def rating(self): rating = 0 for match in self.matches: for stat in match.player_stats: rating += stat.kills return rating
class Concept_class(SurrogatePK, Model): """ defines how concept will be represented """ __tablename__ = 'concept_class' name = Column(db.String(255), unique=True, nullable=False) description = Column(db.String(255), unique=True, nullable=False) creator = Column(db.String(255), nullable=False) date_created = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) retired = Column(db.Boolean, nullable=True) retired_by = Column(db.String(255), nullable=True) date_retired = Column(db.DateTime, nullable=True) retire_reason = Column(db.String(255), nullable=True) uuid = Column(db.String(255), unique=True, nullable=False, default=str(uuid.uuid4())) def __init__(self, name, description, creator, uuid, **kwargs): """ Create instance """ db.Model.__init__(self, name=name, description=description, creator=creator, uuid=uuid, **kwargs)
class Paper(SurrogatePK, Model): __tablename__ = 'papers' id = Column(db.Integer, primary_key=True, autoincrement=True) filename = Column(db.String(100), unique=True, nullable=False) def __init__(self, filename): db.Model.__init__(self, filename=filename) def __repr__(self): return '<Paper({filename!r})'.format(filename=self.filename)
class Event(PkModel): """A role for a user.""" __tablename__ = "event" id = Column(db.Integer, primary_key=True) name = Column(db.String(80)) teams = relationship("Team", backref="event", lazy=True) start_time = Column(DateTime, nullable=True) end_time = Column(DateTime, nullable=True) @property def num_divisions(self): if len(self.teams) == 0: return 0 return sorted(self.teams, key=lambda team: team.division, reverse=True)[0].division def seed_teams(self): # To return a new list, use the sorted() built-in function... sorted_teams = sorted(self.teams, key=lambda team: team.rating, reverse=True) current_division = 0 for i, team in enumerate(sorted_teams): if i % num_teams_per_division == 0: current_division += 1 team.division = current_division print("Team {} is in Division #{}".format(team.name, team.division)) num_divisions = current_division print("Num Divisions: {}".format(num_divisions)) async def refresh_stats(self): for team in self.teams: print("{} - {}".format(self.start_time, self.end_time)) await team.refresh_stats(self.start_time, self.end_time) #match_stats = await get_team_matches(team) #for stat in stats: # player_kills = stat['playerStats']['kills'] # team_placement = stat['playerStats']['teamPlacement'] #team.refresh_stats() @property def leaderboard(self): sorted_teams = sorted(self.teams, key=lambda team: team.rating, reverse=True) for team in sorted_teams: print("{} - {} Score".format(team, team.rating)) return sorted_teams def __repr__(self): return "{}: {} teams are registered".format(self.name, len(self.teams))
class Message(SurrogatePK, Model): __tablename__ = 'messages' user_id = Column(db.Integer, db.ForeignKey('users.id')) body = Column(db.String(140)) timestamp = Column(db.DateTime(timezone=True), index=True, default=maya.now().datetime) user = relationship('User', back_populates='messages', lazy='joined') def __repr__(self): return '<Message {}>'.format(self.body)
class Notification(SurrogatePK, Model): __tablename__ = 'notifications' name = Column(db.String(128), index=True) user_id = Column(db.Integer, db.ForeignKey('users.id')) payload = Column(db.JSON) timestamp = Column(db.DateTime(timezone=True), index=True, default=maya.now().datetime) def __init__(self, name: str, user: '******', payload: Dict) -> None: db.Model.__init__(self, name=name, user_id=user.id, payload=payload) def update(self, commit=True, **kwargs): kwargs['timestamp'] = maya.now().datetime() super().update(commit, **kwargs)
class Vat_receipt(SurrogatePK, Model): __tablename__ = 'vat_receipts' organisation_id = reference_col('organisations', nullable=False) period_key = Column(db.String(4)) processing_date = Column(db.DateTime, nullable = True) payment_indicator = Column(db.String(10)) form_bundle_number = Column(db.String(12)) charge_ref_number = Column(db.String(12)) def __init__(self, organisation_id, period_key, processing_date, **kwargs): db.Model.__init__(self, organisation_id=organisation_id, period_key=period_key, processing_date=processing_date, **kwargs)
class EquityHistoricalData(DefaultBase): equity_id = reference_col("equity") date = Column(db.DateTime, nullable=False) bar_size = Column(db.Enum(BarSizes), default=BarSizes.MIN_1, nullable=False) data_type = Column(db.Enum(HistoricalDataType), nullable=False) open = Column(db.Float, nullable=False) high = Column(db.Float, nullable=False) low = Column(db.Float, nullable=False) close = Column(db.Float, nullable=False) volume = Column(db.Float, nullable=False) bar_count = Column(db.Float, nullable=False) average = Column(db.Float, nullable=False)
class OptionsContractData(DefaultBase): options_contract_id = reference_col("options_contract") date = Column(db.DateTime, nullable=False) bar_size = Column(db.Enum(BarSizes), default=BarSizes.MIN_1, nullable=False) data_type = Column(db.Enum(HistoricalDataType), nullable=False) open = Column(db.Float, nullable=False) high = Column(db.Float, nullable=False) low = Column(db.Float, nullable=False) close = Column(db.Float, nullable=False) volume = Column(db.Float, nullable=False) bar_count = Column(db.Float, nullable=False) average = Column(db.Float, nullable=False)
class Plan(Model): __tablename__ = "plan" user_id = Column(db.Integer, db.ForeignKey('users.id')) name = Column(db.String(120), nullable=False) id = Column(db.Integer, primary_key=True) description = Column(db.String(1200), nullable=True) def makedict(self): return { "userId": self.user_id, "name": self.name, "id": self.id, "description": self.description, }
class User(UserMixin, SurrogatePK, Model): __tablename__ = 'users' username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=True, nullable=False) #: The hashed password password = Column(db.String(128), nullable=True) created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) first_name = Column(db.String(30), nullable=True) last_name = Column(db.String(30), nullable=True) active = Column(db.Boolean(), default=False) is_admin = Column(db.Boolean(), default=False) def __init__(self, username, email, password=None, **kwargs): db.Model.__init__(self, username=username, email=email, **kwargs) if password: self.set_password(password) else: self.password = None def set_password(self, password): self.password = bcrypt.generate_password_hash(password) def check_password(self, value): return bcrypt.check_password_hash(self.password, value) @property def full_name(self): return "{0} {1}".format(self.first_name, self.last_name) def __repr__(self): return '<User({username!r})>'.format(username=self.username)
class Match(PkModel): """A role for a user.""" __tablename__ = "match" id = Column(db.Integer, primary_key=True) external_id = Column(db.Integer) player_stats = relationship("PlayerStat", backref="match", lazy=True) team_id = db.Column(db.Integer, db.ForeignKey('team.id'), nullable=False) def __init__(self, name, **kwargs): """Create instance.""" super().__init__(**kwargs) def __repr__(self): """Represent instance as a unique string.""" return f"<Match({self.external_id})>"
class Role(SurrogatePK, Model): """A role for a user.""" __tablename__ = 'roles' name = Column(db.String(80), unique=True, nullable=False) description = Column(db.String(160), nullable=True) users = relationship('User', secondary=user_roles, backref='roles') def __init__(self, name, **kwargs): """Create instance.""" db.Model.__init__(self, name=name, **kwargs) def __repr__(self): """Represent instance as a unique string.""" return '<Role({name})>'.format(name=self.name)
class Permission(SurrogateBaseKey, Model): """User Permission""" __tablename__ = 'permissions' text = Column(db.String(50), unique=True, nullable=False) def __repr__(self): return '<Permission %r>' % self.text
class Comment(Model, SurrogatePK): __tablename__ = 'comment' id = db.Column(db.Integer, primary_key=True) body = Column(db.Text) createdAt = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) updatedAt = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) author_id = reference_col('userprofile', nullable=False) author = relationship('UserProfile', backref=db.backref('comments')) article_id = reference_col('article', nullable=False) def __init__(self, article, author, body, **kwargs): db.Model.__init__(self, author=author, body=body, article=article, **kwargs)
class Task(PkModel): id = Column(db.String(36), primary_key=True) name = Column(db.String(128), index=True) description = Column(db.String(128)) event_id = Column(db.Integer, db.ForeignKey('event.id')) complete = Column(db.Boolean, default=False) def get_rq_job(self): try: rq_job = rq.job.Job.fetch(self.id, connection=current_app.redis) except (redis.exceptions.RedisError, rq.exceptions.NoSuchJobError): return None return rq_job def get_progress(self): job = self.get_rq_job() return job.meta.get('progress', 0) if job is not None else 100
class User(UserMixin, SurrogatePK, Model, EntityBase): """A user of the app.""" __tablename__ = "users" account = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=True, nullable=False) #: The hashed password password = Column(db.LargeBinary(128), nullable=True) created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) first_name = Column(db.String(30), nullable=True) last_name = Column(db.String(30), nullable=True) active = Column(db.Boolean(), default=False) is_admin = Column(db.Boolean(), default=False) def __init__(self, account, email, password=None, **kwargs): """Create instance.""" db.Model.__init__(self, account=account, email=email, **kwargs) if password: self.set_password(password) else: self.password = None def get_id(self): """获取用户ID""" return self.id 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 f"{self.first_name} {self.last_name}" def __repr__(self): """Represent instance as a unique string.""" return f"<User({self.account!r})>" @classmethod def verify_auth_token(cls, token): data = jwt.decode(token, current_app.config["SECRET_KEY"], algorithms=['HS256']) return cls.query.get(data["id"]) def generate_token(self): return jwt.encode({"id": self.id}, current_app.config["SECRET_KEY"], algorithm='HS256')
class Route(Model): __tablename__ = 'routes' id = Column(db.Integer, primary_key=True) session_id = Column(db.Integer, db.ForeignKey('sessions.id')) timestamp = Column(db.DateTime) type = Column(db.String(32)) grade = Column(db.String(32)) letter = Column(db.String(32)) completion = Column(db.String(32)) falls = Column(db.String(32))
class User(SurrogatePK, Model): __tablename__ = 'users' username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(100), unique=True, nullable=False) password = Column(db.Binary(128), nullable=True) created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) bio = Column(db.String(300), nullable=True) image = Column(db.String(120), nullable=True) token: str = '' def __init__(self, username, email, password=None, **kwargs): """Create instance.""" db.Model.__init__(self, username=username, email=email, **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) def __repr__(self): """Represent instance as a unique string.""" return '<User({username!r})>'.format(username=self.username)
class Player(PkModel): """A role for a user.""" __tablename__ = "player" id = Column(db.Integer, primary_key=True) name = Column(db.String(80)) username = Column(db.String(80)) rating = Column(db.Integer) team_id = db.Column(db.Integer, db.ForeignKey('team.id'), nullable=False) def __init__(self, **kwargs): """Create instance.""" super().__init__(**kwargs) def __repr__(self): """Represent instance as a unique string.""" return f"<Player({self.name})>"
class PlayerStat(PkModel): """A role for a user.""" __tablename__ = "player_statistic" id = Column(db.Integer, primary_key=True) username = Column(db.String(80)) kills = Column(db.Integer) placement = Column(db.Integer) match_id = db.Column(db.Integer, db.ForeignKey('match.id'), nullable=True) team_id = db.Column(db.Integer, db.ForeignKey('team.id'), nullable=True) def __init__(self, **kwargs): """Create instance.""" super().__init__(**kwargs) def __repr__(self): """Represent instance as a unique string.""" return f"<PlayerStat({self.username})>"
class Role(SurrogatePK, Model): __tablename__ = 'roles' name = Column(db.String(80), unique=True, nullable=False) user_id = ReferenceCol('users', nullable=True) user = relationship('User', backref='roles') def __init__(self, name, **kwargs): db.Model.__init__(self, name=name, **kwargs) def __repr__(self): return '<Role({name})>'.format(name=self.name)
class User(Model, UserMixin): __tablename__ = 'users' id = Column(db.Integer, primary_key=True) email = Column(db.String(64), index=True, unique=True) password_hash = Column(db.String(128)) role_id = Column(db.Integer, db.ForeignKey('roles.id')) sessions = relationship('Session', backref='user', lazy='dynamic') def __repr__(self): return f'<User {self.email}, {self.id}>' @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)
class Organisation(SurrogatePK, Model): """docstring for ClassName""" __tablename__ = 'organisations' uuid = Column(db.String(36), unique=True, nullable =False ) code = Column(db.String(3), unique=True, nullable=False) vrn = Column(db.String(9), unique=True) name = Column(db.String(50), unique=True) # Relationships users = relationship('User', backref='organisation') vat_returns = relationship('Vat_return', backref='organisation') def __init__(self, code, **kwargs): self.uuid = str(uuid.uuid4()) db.Model.__init__(self, code=code, **kwargs) def __repr__(self): """Represent instance as a unique string.""" return '<Organisation({name})>'.format(name=self.name)
class Group(SurrogateBaseKey, Model): """User Group""" __tablename__ = 'groups' name = Column(db.String(20), unique=True, nullable=False) users = relationship( 'User', secondary=GROUPS_USERS, lazy='subquery', backref=db.backref('groups', lazy=True)) permissions = relationship( 'Permission', secondary=GROUPS_PERMISSIONS, lazy='subquery', backref=db.backref('groups', lazy=True)) def __repr__(self): return '<Group %r>' % self.name
class User(SurrogateBaseKey, Model): """User Model""" __tablename__ = 'users' public_id = Column(db.String(50), unique=True, nullable=False) username = Column(db.String(64), unique=True, index=True, nullable=False) email = Column(db.String(120), unique=True, index=True, nullable=False) password_hash = Column(db.String(128)) nickname = Column(db.String(20), default='no name') created_on = Column(db.DateTime, nullable=False, default=datetime.utcnow) def __repr__(self): return '<User %r>' % self.username def set_password(self, password): """Set password hash.""" self.password_hash = generate_password_hash(password) def check_password(self, password): """Check password hash.""" return check_password_hash(self.password_hash, password) def generate_jwt(self, expries_in=24*60**2): """Generate JSON Web Token :expries_in: Validaty period :returns: JSON Web Token string """ return jwt.encode( { 'user_id': self.id, 'uuid': self.public_id, 'permissions': [permission.text for group in self.groups for permission in group.permissions], 'exp': time() + expries_in }, current_app.config['SECRET_KEY'], algorithm='HS256' ).decode('utf-8') @staticmethod def verify_jwt(token): """Verify JSON Web Token :token: JSON Web Token :returns: data dict or None """ try: data = jwt.decode( token, current_app.config['SECRET_KEY'], algorithms=['HS256'] ) except jwt.exceptions.DecodeError: return None return data