class User(db.Model): id = db.Column(db.Integer, primary_key=True) user_name = db.Column(db.String(20), nullable=False) email = db.Column(db.String(50), nullable=False) first_name = db.Column(db.String(20), nullable=False) last_name = db.Column(db.String(20), nullable=False) password = db.Column(BYTEA) interests = db.relationship('Interest', secondary=user_interests) friendship = db.relationship('Friendship', secondary=user_friendship) def serialize_short(self): return { 'id': self.id, 'user_name': self.user_name, 'first_name': self.first_name, 'last_name': self.last_name, 'email': self.email, 'interests': [interest.serialize_short() for interest in self.interests] }
class Response(BaseModel): __tablename__ = "responses" id = db.Column( UUID(as_uuid=True), server_default=sqlalchemy.text("gen_random_uuid()"), primary_key=True, ) challenge = db.relationship("Challenge", backref="responses") challenge_id = db.Column(UUID(as_uuid=True), db.ForeignKey("challenges.id"), primary_key=True) user = db.relationship("User", backref="responses") user_id = db.Column(UUID(as_uuid=True), db.ForeignKey("users.id"), primary_key=True) video = db.relationship("Video", backref=backref("response", uselist=False)) video_id = db.Column(UUID(as_uuid=True), db.ForeignKey("videos.id"), 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 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 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 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 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 Project(db.Model): __tablename__ = 'projects' id = db.Column(db.Integer, primary_key=True) id_project42 = db.Column(db.Integer, unique=True, nullable=False) name = db.Column(db.String(100), nullable=False) slug = db.Column(db.String(100), nullable=False) tier = db.Column(db.Integer, nullable=False) active = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.true()) # relationship with 'Mentors' table, Mentor Model Class mentors = db.relationship('Mentor', backref=backref('project', lazy='joined'), lazy=True) def __init__(self, id_project42, name, slug, tier, active=True): self.id_project42 = id_project42 self.name = name self.slug = slug self.tier = tier self.active = active @classmethod def queryProject(cls, id42=0, name=None): if id42 is not 0: query = cls.query.filter_by(id_project42=id42).first() if query is None: return None, "No project with 42 id {}".format(id42) elif name: query = cls.query.filter_by(name=name).first() if query is None: return None, "No project named {}".format(name) else: return None, "No data provided to query" return project_schema.dump(query).data, None @classmethod def queryAll(cls): query = cls.query.all() if query is None: return None, "No projects exist" return projects_schema.dump(query).data, None
class Event(db.Model): __tablename__ = 'events' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) description = db.Column(db.Text) creator_id = db.Column(db.ForeignKey('user.id')) interests = db.relationship('Interest', secondary=event_interests) def serialize_short(self): return { 'id': self.id, 'title': self.title, 'description': self.description, 'interests': [interest.serialize_short() for interest in self.interests] }
class FinancialSummary(db.Model): """ Financial Summary model """ __tablename__ = 'financial_summaries' id = db.Column(db.Integer, primary_key=True) company_id = db.Column(db.Integer, db.ForeignKey('company_profiles.id')) capital_currency = db.Column(db.String(50)) market_cap = db.Column(db.BigInteger) par_value = db.Column(db.BigInteger) equity = db.Column(db.BigInteger) listing_volume = db.Column(db.BigInteger) listed_date = db.Column(db.DateTime) initial_listed_price = db.Column(db.BigInteger) created_at = db.Column(db.DateTime(timezone=True), server_default=func.now()) company = db.relationship('CompanyProfile', uselist=False, backref='financial_summary') def __repr__(self): return 'company_id : {}'.format(self.company_id)
class Report(db.Model): id = db.Column(db.Integer, primary_key=True) reporter_id = db.Column(db.Integer) timestamp = db.Column(db.Integer) longitude = db.Column(db.Float) latitude = db.Column(db.Float) report_type = db.Column(db.String) description = db.Column(db.String) video_id = db.Column(db.Integer, db.ForeignKey('video.id')) video = db.relationship('Video', backref='report', uselist=False) images = db.relationship('Image', backref='report') analysis_complete = db.Column(db.Boolean, default=False) car_color = db.Column(db.String) probability = db.Column(db.Integer) profile_id = db.Column(db.Integer, db.ForeignKey('profile.id')) def __init__(self, reporter_id, report_type, timestamp, longitude, latitude, analysis_complete=False, video_id=None): self.reporter_id = reporter_id self.report_type = report_type self.timestamp = timestamp self.longitude = longitude self.latitude = latitude self.analysis_complete = analysis_complete self.video_id = video_id @staticmethod def validate_json(data): missing = [] if 'user_id' not in data: missing.append('user_id') if 'timestamp' not in data: missing.append('timestamp') if 'report_type' not in data: missing.append('report_type') if 'location' not in data: missing.append('location') if 'longitude' not in data.get('location'): missing.append('longitude') if 'latitude' not in data.get('location'): missing.append('latitude') if len(missing): return False, missing else: return True, None def to_dict(self): obj = {} obj['id'] = self.id obj['reporter_id'] = self.reporter_id obj['timestamp'] = self.timestamp obj['location'] = {'lat': self.longitude, 'lng': self.latitude} obj['video_url'] = self.video.url if self.video is not None else '' obj['image_urls'] = [image.url for image in self.images] obj['analysis_complete'] = self.analysis_complete obj['car_color'] = self.car_color if self.car_color is not None else '' obj['description'] = self.description if self.description is not None else '' obj['probability'] = self.probability return obj
class Mentor(db.Model): __tablename__ = 'mentors' id = db.Column(db.Integer, primary_key=True) id_project42 = db.Column(db.Integer, db.ForeignKey('projects.id_project42'), nullable=False) id_user42 = db.Column(db.Integer, db.ForeignKey('users.id_user42'), nullable=False) finalmark = db.Column(db.Integer, nullable=False, server_default='0') abletomentor = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.false()) last_appointment = db.Column(db.DateTime(timezone=True)) active = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.false()) started_at = db.Column(db.DateTime(timezone=True), nullable=False, server_default=sa.func.now()) # relationship with 'Appointments' table, Appointment Model Class appointments = db.relationship('Appointment', backref=backref('mentor', lazy='joined'), lazy=True) def __init__(self, id_project42, id_user42, finalmark): self.id_project42 = id_project42 self.id_user42 = id_user42 self.finalmark = 0 if finalmark is None else finalmark @classmethod def queryAll(cls): query = cls.query.all() if not query: return None, "No mentors exist" return mentors_schema.dump(query).data, None @classmethod def queryById(cls, mentorId): query = cls.query.filter_by(id=mentorId).first() if not query: return None, "No mentor with id {} was found".format(mentorId) return mentor_schema.dump(query).data, None @classmethod def queryManyByProject(cls, id): query = cls.query.filter_by(id_project42=id).all() if not query: return None, "No mentors for project {}".format(id) return mentors_schema.dump(query).data, None @classmethod def queryManyByUser(cls, id): query = cls.query.filter_by(id_user42=id).all() if not query: return None, "No mentors for project {}".format(id) return mentors_schema.dump(query).data, None @classmethod def queryByFilter(cls, **kwargs): query = cls.query.filter_by(**kwargs).first() if not query: return None, "No mentor found" return mentor_schema.dump(query).data, None @classmethod def queryManyByFilter(cls, **kwargs): query = cls.query.filter_by(**kwargs).all() if not query: return None, "No mentors found" return mentors_schema.dump(query).data, None
class DriverModel(db.Model): __tablename__ = 'drivers' id = db.Column(db.Integer, primary_key=True, index=True) first_name = db.Column(db.String(64)) last_name = db.Column(db.String(64), unique=True, index=True) number = db.Column(db.Integer, unique=True) team_id = db.Column(db.Integer, db.ForeignKey('teams.id')) team = db.relationship('TeamModel') country = db.Column(db.String(64)) podium = db.Column(db.Integer, default=0) points = db.Column(db.Integer, default=0) championships = db.Column(db.Integer, default=0) birthday = db.Column(db.DateTime) def __init__(self, first_name, last_name, number, team_id, country, podium=0, points=0, championships=0, birthday=date(1990, 1, 1)): self.first_name = first_name self.last_name = last_name self.number = number self.team_id = team_id self.country = country self.podium = podium self.points = points self.championships = championships self.birthday = birthday def json(self): return { 'id': self.id, 'name': "{} {}".format(self.first_name, self.last_name), 'number': self.number, 'team_id': self.team_id, 'country': self.country, 'podiums': self.podium, 'points': self.points, 'championships': self.championships, 'birthday': '{0.month}/{0.day}/{0.year}'.format(self.birthday), } @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first() @classmethod def find_by_number(cls, number): return cls.query.filter_by(number=number).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): db.session.add(self) db.session.commit() @db_check_or_return_500 def delete_from_db(self): db.session.delete(self) db.session.commit()
class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) id_user42 = db.Column(db.Integer, unique=True, nullable=False) login = db.Column(db.String(45), 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') last_seen = db.Column(db.DateTime(timezone=True), nullable=False, server_default=sa.func.now()) active = db.Column(db.Boolean, nullable=False, server_default=sa.sql.expression.true()) # relationship with 'Mentors' table, Mentor Model Class mentor = db.relationship('Mentor', backref=backref('user', lazy='joined'), lazy=True) # relationship with 'Appointments' table, Appointment Model Class appointments = db.relationship('Appointment', backref=backref('user', lazy='joined'), lazy=True) def __init__(self, id_user42, login): self.id_user42 = id_user42 self.login = login @classmethod def queryByAll(cls): query = cls.query.all() if not query: return None, "User table is empty" return users_schema.dump(query).data, None @classmethod def queryById(cls, userId): query = cls.query.filter_by(id=userId).first() if not query: return None, "No user with id {} was found".format(id) return user_schema.dump(query).data, None @classmethod def queryById_user42(cls, userId): query = cls.query.filter_by(id_user42=userId).first() if not query: return None, "No user with id_user42 {} was found".format(userId) return user_schema.dump(query).data, None @classmethod def queryByLogin(cls, login): query = cls.query.filter_by(login=login).first() if not query: return None, "No user with login {} was found".format(login) return user_schema.dump(query).data, None @classmethod def queryByFilter(cls, **kwargs): query = cls.query.filter_by(**kwargs).first() if not query: return None, "No user found" return user_schema.dump(query).data, None
class TeamModel(db.Model): __tablename__ = 'teams' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True, index=True) base = db.Column(db.String(64)) chief = db.Column(db.String(64)) car = db.Column(db.String(64)) power_unit = db.Column(db.String(64)) since = db.Column(db.Integer) championships = db.Column(db.Integer, default=0) drivers = db.relationship('DriverModel', lazy='dynamic') def __init__(self, name, base, chief, car, power_unit, since=0, championships=0): self.name = name self.base = base self.chief = chief self.car = car self.power_unit = power_unit self.since = since self.championships = championships def json(self): return { 'id': self.id, 'name': self.name, 'base': self.base, 'chief': self.chief, 'car': self.car, 'power_unit': self.power_unit, 'founded': self.since, 'championships': self.championships, 'drivers': [d.json() for d in self.drivers.all()], } @classmethod def find_all(cls): return cls.query.all() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first() @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()