class Auditable(db.Model): __abstract__ = True created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow) created_by = db.Column(db.String(64)) updated_at = db.Column(db.DateTime, default=datetime.datetime.utcnow) updated_by = db.Column(db.String(64))
class WishModel(BaseModel, db.Model): """ Wish Model """ __tablename__ = 'wishes' __table_args__ = (db.UniqueConstraint('name', 'owner_id', 'is_active'), ) name = db.Column(db.String(128), nullable=False) price = db.Column(db.Numeric, nullable=False) description = db.Column(db.String(256), nullable=True) owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) def __init__(self, name: str, price: float, owner_id: int, description: str = None): self.name = name self.price = abs(price) self.owner_id = owner_id self.description = description super(WishModel, self).__init__() def __str__(self): return '{} - {} - $ {}'.format(self.id, self.name, self.price)
class MentorStat(db.Model): __tablename__ = 'mentorstats' id = db.Column(db.Integer, primary_key=True) id_mentor = db.Column(db.Integer, db.ForeignKey('mentors.id'), nullable=False) rating = db.Column(db.Numeric(10, 2, asdecimal=False), nullable=False, server_default='0.00') totalappointments = db.Column(db.Integer, nullable=False, server_default='0') cancelledappointments = db.Column(db.Integer, nullable=False, server_default='0') # relationship with 'mentors' table, Mentor Model Class mentor = db.relationship('Mentor', backref=backref('mentorstat', lazy='joined', uselist=False), lazy=True) def __init__(self, id_mentor): self.id_mentor = id_mentor
class Challenge(BaseModel): __tablename__ = "challenges" __table_args__ = (db.Index("challenges_by_user_id_listed", "user_id", "listed"), ) id = db.Column( UUID(as_uuid=True), server_default=sqlalchemy.text("gen_random_uuid()"), primary_key=True, ) title = db.Column(db.Unicode(length=255), nullable=False) instructions = db.Column(db.UnicodeText, nullable=False) grading_notes = db.Column(db.UnicodeText, nullable=False) listed = db.Column(db.Boolean, default=False, nullable=False, index=True) user = db.relationship("User", backref="challenges") user_id = db.Column(UUID(as_uuid=True), db.ForeignKey("users.id")) video = db.relationship("Video", backref=backref("challenges", uselist=False)) video_id = db.Column(UUID(as_uuid=True), db.ForeignKey("videos.id"), nullable=True) deleted_at = db.Column(db.DateTime(timezone=True), nullable=True) created_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), nullable=False) updated_at = db.Column( db.DateTime(timezone=True), server_default=func.now(), onupdate=datetime.utcnow, nullable=False, )
class Image(db.Model): id = db.Column(db.Integer, primary_key=True) path = db.Column(db.String) url = db.Column(db.String) ext = db.Column(db.String) report_id = db.Column(db.Integer, db.ForeignKey('report.id'), nullable=False) @classmethod def from_arr(cls, arr, report_id): arr = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR) image = cls(report_id=report_id) db.session.add(image) db.session.commit() ext = '.jpg' file_id = uuid.uuid4().int filename = str(file_id) + ext abs_fpath = os.path.join(app.config['MEDIA_FOLDER'], filename) cv2.imwrite(abs_fpath, arr) rel_path = os.path.join(os.path.basename(app.config['MEDIA_FOLDER']), filename) url = os.path.join('image', str(image.id)) image.path = rel_path image.url = url image.ext = ext db.session.commit() return image
class Task(db.Model): # look primary key is STRING not Integer WTF!? :D # because this id is NOT SQLAlchemy id # but RQ job identificator id = db.Column(db.String(36), primary_key=True) name = db.Column(db.String(128), index=True) description = db.Column(db.String(128)) complete = db.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 @classmethod def launch_task(cls, name, description): rq_job = current_app.task_queue.enqueue('app.tasks.' + name) print('\n---job_id!!') print(rq_job.get_id()) task = cls(id=rq_job.get_id(), name=name, description=description) print(task) db.session.add(task) print('----') return task
class Images(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) # TODO create a unique index path = db.Column(db.String(1024)) def serialize(self): ret = dict() ret['name'] = self.name ret['path'] = self.path return ret @classmethod def update(cls, model, path, name): model.name = name model.path = path db.session.commit() return model @classmethod def create(cls, path, name): model = cls() model.name = name model.path = path db.session.add(model) db.session.commit() return model
class BaseModel: """ Base Model """ id = db.Column(db.Integer, primary_key=True) is_active = db.Column(db.Boolean, default=True) created_at = db.Column(db.DateTime) modified_at = db.Column(db.DateTime) def __init__(self): self.created_at = datetime.utcnow() self.modified_at = datetime.utcnow() def save(self): db.session.add(self) db.session.commit() def update(self, **kwargs): for key, item in kwargs.items(): setattr(self, key, item) self.modified_at = datetime.utcnow() db.session.commit() def delete(self): self.update(is_active=False) def __repr(self): return '<id {}>'.format(self.id)
class AppRequest(db.Model): __tablename__ = "apprequests" id = db.Column(db.Integer, primary_key=True) appversion = db.Column(db.Integer, nullable=False) customer = db.Column(db.Integer, nullable=False, server_default='0') car = db.Column(db.Integer, nullable=False, server_default='0') developer = db.Column(db.Integer, nullable=False, server_default='0') admincomment = db.Column(db.Text) dateclosed = db.Column(db.DateTime) datecreated = db.Column(db.DateTime, server_default=sa.func.now()) status = db.Column(db.Integer, nullable=False, server_default='1') requesttype = db.Column(db.Integer, nullable=False) def __init__(self, requesttype, appversion, customer=0, car=0, developer=0): self.appversion = appversion self.customer = customer self.car = car self.developer = developer self.requesttype = requesttype
class Token(db.Model): id = db.Column(db.Integer, primary_key=True) token = db.Column(db.String(256)) expire = db.Column(db.Date()) def delete_myself(self): db.session.delete(self) db.session.commit()
class RequestType(db.Model): __tablename__ = "requesttypes" id = db.Column(db.Integer, primary_key=True) requesttype = db.Column(db.String(40), nullable=False) def __init__(self, requesttype): self.requesttype = requesttype
class Video(db.Model): id = db.Column(db.Integer, primary_key=True) path = db.Column(db.String) url = db.Column(db.String) ext = db.Column(db.String) @property def filename(self): return "{}.{}".format(self.id, self.ext)
class Account(db.Model): __tablename__ = "accounts" id = db.Column(db.Integer, primary_key=True) firstname = db.Column(db.String(50), nullable=False) lastname = db.Column(db.String(50), nullable=False) username = db.Column(db.String(50), nullable=False) password = db.Column(db.Text, nullable=False) customer = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.true()) developer = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.false()) admin = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.false()) active = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.true()) def __init__(self, firstname, lastname, username, password): self.firstname = firstname self.lastname = lastname self.username = username self.password = password
class SetRecord(Auditable): __tablename__ = 'set_record' id = db.Column(db.Integer, primary_key=True) set_number = db.Column(db.Integer) score = db.Column(db.Integer) lift_record_id = db.Column(db.Integer, db.ForeignKey('lift_record.id')) def __init__(self, set_number, score): self.set_number = set_number self.score = score
class User(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), index=True, unique=True, nullable=False) password = db.Column(db.String(128), nullable=False) def __init__(self, email, password): self.email = email self.password = password def __repr__(self): return '<User {}>'.format(self.email)
class Interest(db.Model): __tablename__ = 'interests' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) def serialize_short(self): return { 'id': self.id, 'title': self.title, }
class CarUser(db.Model): __tablename__ = "carusers" id = db.Column(db.Integer, primary_key=True) car = db.Column(db.Integer, nullable=False) account = db.Column(db.Integer, nullable=False) created = db.Column(db.DateTime, nullable=False, server_default=sa.func.now()) def __init__(self, car, account): self.car = car self.account = account
class ScoreTypes(db.Model): __tablename__ = 'score_types' def __init__(self, code, label): self.code = code self.label = label id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(64), index=True, unique=True) label = db.Column(db.String(64)) def __repr__(self): return '<id {}>'.format(self.id)
class ApplicationDeveloper(db.Model): __tablename__ = "applicationdevelopers" id = db.Column(db.Integer, primary_key=True) appid = db.Column(db.Integer, nullable=False) accountid = db.Column(db.Integer, nullable=False) active = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.true()) def __init__(self, appid, accountid): self.appid = appid self.accountid = accountid
class Message(db.Model): created_at = db.Column(db.DateTime, nullable=False, default=lambda: datetime.utcnow()) updated_at = db.Column( db.DateTime, nullable=False, default=lambda: datetime.utcnow(), onupdate=lambda: datetime.utcnow() ) status = db.Column( db.Enum(MessageStatus, values_callable=lambda enum: [e.value for e in enum], native_enum=False), default=MessageStatus.CONFIRMED) id = db.Column(db.Integer, primary_key=True) payload = db.Column(db.JSON) def __repr__(self): return f'<Message id:{self.id}>'
class CarModel(db.Model): __tablename__ = "carmodels" id = db.Column(db.Integer, primary_key=True) cartype = db.Column(db.String(100)) model = db.Column(db.String(100)) year = db.Column(db.Integer) description = db.Column(db.Text) def __init__(self, cartype, model, year, description=""): self.cartype = cartype self.model = model self.year = year self.description = description
class Profile(db.Model): id = db.Column(db.Integer, primary_key=True) license_plate = db.Column(db.String, unique=True) vehicle = db.Column(db.String) reports = db.relationship('Report', backref='profile') def to_dict(self): obj = {} obj['id'] = self.id obj['license_plate'] = self.license_plate obj['vehicle'] = self.vehicle obj['reports'] = [r.to_dict() for r in self.reports] return obj
class Result(db.Model): __tablename__ = 'results' id = db.Column(db.Integer, primary_key=True) url = db.Column(db.String()) result_all = db.Column(JSON) result_no_stop_words = db.Column(JSON) def __init__(self, url, result_all, result_no_stop_words): self.url = url self.result_all = result_all self.result_no_stop_words = result_no_stop_words def __repr__(self): return '<id {}>'.format(self.id)
class Affiliate(Auditable): __tablename__ = 'affiliate' id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(64), index=True, unique=True) name = db.Column(db.String(64)) address = db.Column(db.Text, index=False, unique=False) def __init__(self, code, name, address = None): self.name = name self.code = code self.address = address def __repr__(self): return '<id {}>'.format(self.id)
class Movement(db.Model): __tablename__ = 'movement' id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(5)) label = db.Column(db.String(64), index=True, unique=True) standard = db.Column(db.String(64)) load_measurement = db.Column(db.Enum(MeasurementEnum)) def __init__(self, code, label, load=None): self.code = code self.label = label self.load_measurement = load def __repr__(self): return '<id {}>'.format(self.id)
class UserModel(BaseModel, db.Model): """ User Model """ __tablename__ = 'users' full_name = db.Column(db.String(128), nullable=True) email = db.Column(db.String(128), unique=True, nullable=False) password = db.Column(db.String(128), nullable=True) address = db.Column(JSON) wishes = db.relationship('WishModel', backref='users', lazy=True) def __init__(self, full_name: str, email: str, password: str, address: dict): self.full_name = full_name self.email = email self.password = password self.address = address super(UserModel, self).__init__() def save(self): self.password = self.__generate_password_hash(self.password) super(UserModel, self).save() def update(self, **kwargs): super(UserModel, self).update(**kwargs) def set_password(self, password): password_hash = self.__generate_password_hash(password) super(UserModel, self).update(**{'password': password_hash}) @staticmethod def __generate_password_hash(password): return bcrypt.generate_password_hash(password, rounds=10).decode('utf-8') def check_password_hash(self, password): return bcrypt.check_password_hash(self.password, password) @property def first_name(self): return self.full_name.split(' ')[0] if self.full_name else '' def __str__(self): return '<{} - {}>'.format(self.full_name, self.email)
class Benchmark(db.Model): __tablename__ = 'benchmark' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) workout_type_id = db.Column(db.Integer, db.ForeignKey('workout_types.id')) workout_type = relationship('WorkoutTypes') score_type_id = db.Column(db.Integer, db.ForeignKey('score_types.id')) score_type = relationship('ScoreTypes') movements = relationship('Movement', secondary=benchmark_association_table) def __init__(self, name, workout_type, score_type): self.name = name self.workout_type = workout_type self.workout_type_id = workout_type.id self.score_type = score_type self.score_type_id = score_type.id
class LiftRecord(Auditable): __tablename__ = 'lift_record' id = db.Column(db.Integer, primary_key=True) lift_id = db.Column(db.Integer, db.ForeignKey('lift.id')) lift = relationship('Lift', back_populates='lift_records') number_of_sets = db.Column(db.Integer) reps_per_set = db.Column(db.Integer) date = db.Column(db.DateTime, default = datetime.datetime.utcnow) sets = relationship('SetRecord') def __init__(self, number_of_sets, reps_per_set): self.number_of_sets = number_of_sets self.reps_per_set = reps_per_set def get_highest(self): return max(sets, key=lambda x: x.score)
class Communities(db.Model): __tablename__ = 'communities' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) description = db.Column(db.Text) userscount = db.Column(db.Integer) # Union between this table & interests name def serialize_short(self): return { 'id': self.id, 'name': self.name, 'description': self.description, 'userscount': self.userscount }
class WorkoutTypes(db.Model): __tablename__ = 'workout_types' id = db.Column(db.Integer, primary_key=True) code = db.Column(db.Enum(WorkoutTypeEnum)) label = db.Column(db.String(64), index=True, unique=True) category = db.Column(db.Enum(WorkoutCategoryEnum)) description = db.Column(db.String(64), index=False, unique=False) def __init__(self, code, label, category, description = None): self.code = code self.label = label self.category = category self.description = description def __repr__(self): return '<id {}>'.format(self.id)