class AuthorModel(db.Model): # Specifying table __tablename__ = "author" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) profile_image = db.Column(db.Text()) videos = db.relationship('VideoModel', secondary=video_author, backref=db.backref('authors', lazy='dynamic')) def save_to_db(self) -> None: '''Add author to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes author from the database.''' db.session.delete(self) db.session.commit() @classmethod def find_by_name(cls, name: str) -> 'AuthorModel': return cls.query.filter_by(name=name).first()
class CategoryModel(db.Model): # Specifying table __tablename__ = "category" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text()) section = db.relationship('SectionModel', secondary=category_section, backref=db.backref('category', lazy='dynamic')) def __init__(self, title): self.title = title @classmethod def find_by_title(cls, title: str) -> 'CategoryModel': return cls.query.filter_by(title=title.capitalize()).first() def save_to_db(self) -> None: '''Add category to database''' db.session.add(self) db.session.commit() def add_category_section(self, section) -> None: self.section.append(section) db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes category from the database.''' db.session.delete(self) db.session.commit()
class SectionModel(db.Model): # Specifying table __tablename__ = "section" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(64), unique=True) videos = db.relationship('VideoModel', secondary=section_video, backref=db.backref('sections', lazy='dynamic')) def init(self, title): self.title = title def save_to_db(self) -> None: '''Add section to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes section from the database.''' db.session.delete(self) db.session.commit() def add_video(self, video: 'VideoModel') -> None: self.videos.append(video) db.session.add(self) db.session.commit()
class InstitutionModel(db.Model): # Specifying table __tablename__ = "institution" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text()) district = db.Column(db.String(50)) state = db.Column(db.String(50)) affiliation_code = db.Column(db.String(10)) active_applicant = db.Column(db.Integer) total_applicant = db.Column(db.Integer) is_school = db.Column(db.Boolean) is_college = db.Column(db.Boolean) def __init__(self, name, institute_type, state, district, affiliation_code): self.name = name self.state = state self.district = district self.affiliation_code = affiliation_code self.is_college = True if institute_type == 1 else False self.is_school = True if institute_type == 0 else False def save_to_db(self) -> None: '''Add institution to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes institution from the database.''' db.session.delete(self) db.session.commit()
class SectionModel(db.Model): # Specifying table __tablename__ = "section" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) # NOTE: won't have much sections (compared to videos), not need index at this point title = db.Column(db.String(64), unique=True, nullable=False) videos = db.relationship( "VideoModel", secondary=section_video, backref=db.backref("sections", lazy="dynamic", cascade="all, delete"), ) def init(self, title): self.title = title def save_to_db(self) -> None: """Add section to database""" try: db.session.add(self) db.session.commit() except Exception: db.rollback() raise def delete_from_db(self) -> None: """Deletes section from the database.""" db.session.delete(self) db.session.commit() def update(self, **kwargs) -> None: """Updates section""" for field, field_value in kwargs.items(): if hasattr(self, field): setattr(self, field, field_value) try: db.session.commit() return self except Exception: db.session.rollback() raise def add_video(self, video: "VideoModel") -> None: self.videos.append(video) try: db.session.add(self) db.session.commit() except Exception: db.rollback() raise
class CategoryModel(db.Model): # Specifying table __tablename__ = "category" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) # NOTE: won't have much categories (compared to videos), not need index at this point title = db.Column(db.Text(), unique=True, nullable=False) section = db.relationship( "SectionModel", secondary=category_section, backref=db.backref("category", lazy="dynamic"), cascade="all, delete", passive_deletes=True, ) def __init__(self, title): self.title = title @classmethod def find_by_title(cls, title: str) -> "CategoryModel": return cls.query.filter_by(title=title.capitalize()).first() def save_to_db(self) -> None: """Add category to database""" self._add_and_commit() def add_sections(self, sections) -> None: """Add category section instance""" self.section.extend(sections) self._add_and_commit() def add_category_section(self, section) -> None: self.section.append(section) self._add_and_commit() def delete_from_db(self) -> None: """Deletes category from the database.""" db.session.delete(self) db.session.commit() def _add_and_commit(self): try: db.session.add(self) db.session.commit() except Exception as e: db.session.rollback() raise e def json(self): return {"id": self.id, "title": self.title}
class AuthorModel(db.Model): # Specifying table __tablename__ = "author" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), index=True) profile_image = db.Column(db.Text()) videos = db.relationship( "VideoModel", secondary=video_author, backref=db.backref("authors", lazy="dynamic"), ) def json(self): return { "id": self.id, "name": self.name, "profile_image": self.profile_image } @classmethod def find_by_name(cls, name: str) -> "AuthorModel": return cls.query.filter_by(name=name).first() def save_to_db(self) -> None: """Add author to database""" try: db.session.add(self) db.session.commit() except Exception: db.session.rollback() raise def delete_from_db(self) -> None: """Deletes author from the database.""" db.session.delete(self) db.session.commit() def add_video(self, video: "VideoModel") -> None: try: self.videos.append(video) db.session.add(self) db.session.commit() except Exception: db.session.rollback() raise
class TaskModel(db.Model): # Specifying database table used for GoalModel __tablename__ = "tasks" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(30)) stage_id = db.Column(db.Integer, db.ForeignKey('stages.id'), nullable=False) def __init__(self, stage_id, title='mystage'): """Initialises userModel class with name. """ self.title = title self.stage_id = stage_id def json(self): """Returns Usermodel object in json format.""" return {"id": self.id, "title": self.title, "stage_id": self.stage_id} def __repr__(self): """Returns the user's name and username. """ return f"Task {self.title}" @classmethod def find_by_id(cls, _id: int) -> 'TaskModel': """Returns the goal that has the id we searched for. """ return cls.query.filter_by(id=_id).first() @classmethod def is_empty(cls) -> bool: """Returns a boolean if the GoalModel is empty or not. """ return cls.query.first() is None def save_to_db(self) -> int: """Adds a goal to the database. """ db.session.add(self) db.session.flush() id = self.id db.session.commit() return id def delete_from_db(self) -> None: """Deletes a user from the database. """ db.session.delete(self) db.session.commit()
class UserModel(db.Model): # Specifying table __tablename__ = "users" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30)) username = db.Column(db.String(30)) email = db.Column(db.String(100)) password_hash = db.Column(db.String(100)) registration_date = db.Column(db.Integer) terms_and_conditions_checked = db.Column(db.Boolean) access_rights = db.Column(db.Integer) is_email_verified = db.Column(db.Boolean) email_verification_date = db.Column(db.Integer) def json(self): '''Returns UserModel object in json format.''' return { "id": self.id, "name": self.name, "username": self.username, "email": self.email, "password_hash": self.password_hash, "registration_date": self.registration_date, "terms_and_conditions_checked": self.terms_and_conditions_checked, "access_rights": 0, # access_rights will have to be given by admin "is_email_verified": is_email_verified, "email_verification_date": email_verification_date, } def find_by_id(cls, _id: int) -> 'UserModel': '''Returns a particular user of given id.''' return cls.query.filter_by(id=_id).first() def save_to_db(self) -> None: '''Add user to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes user from the database.''' db.session.delete(self) db.session.commit()
class CategoryModel(db.Model): # Specifying table __tablename__ = "category" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text()) section = db.relationship( "SectionModel", secondary=category_section, backref=db.backref("category", lazy="dynamic"), ) def __init__(self, title): self.title = title @classmethod def find_by_title(cls, title: str) -> "CategoryModel": return cls.query.filter_by(title=title.capitalize()).first() def save_to_db(self) -> None: """Add category to database""" db.session.add(self) db.session.commit() def add_sections(self, sections) -> None: """Add category section instance""" self.section.extend(sections) db.session.add(self) db.session.commit() def add_category_section(self, section) -> None: self.section.append(section) db.session.add(self) db.session.commit() def delete_from_db(self) -> None: """Deletes category from the database.""" db.session.delete(self) db.session.commit() def json(self): return {"id": self.id, "title": self.title}
class GoalModel(db.Model): # Specifying database table used for GoalModel __tablename__ = "goals" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30)) stages = db.relationship('StageModel', backref='goal', lazy=True) def __init__(self, name='MyGoal'): """Initialises userModel class with name. """ self.name = name def json(self): """Returns Usermodel object in json format.""" return {"id": self.id, "name": self.name} def __repr__(self): """Returns the user's name and username. """ return f"Goal {self.name}" @classmethod def find_by_id(cls, _id: int) -> 'GoalModel': """Returns the goal that has the id we searched for. """ return cls.query.filter_by(id=_id).first() @classmethod def is_empty(cls) -> bool: """Returns a boolean if the GoalModel is empty or not. """ return cls.query.first() is None def save_to_db(self) -> int: """Adds a goal to the database. """ db.session.add(self) db.session.flush() id = self.id db.session.commit() return id def delete_from_db(self) -> None: """Deletes a user from the database. """ db.session.delete(self) db.session.commit()
class ModeratorRequestModel(db.Model): # Specifying table __tablename__ = "moderator_request" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) donor_id = db.Column(db.Integer, db.ForeignKey("user.id")) donor = db.relationship( UserModel, backref="moderator_request", primaryjoin="ModeratorRequestModel.donor_id == UserModel.id", ) application_id = db.Column(db.Integer, db.ForeignKey("application.id")) application = db.relationship( ApplicationModel, backref="moderator_request", primaryjoin= "ModeratorRequestModel.application_id == ApplicationModel.id", ) accepted = db.Column(db.Boolean) mod_email = db.Column(db.String(70)) def __init__(self, donor, invitee_email, unique_code): self.invitee_email = invitee_email self.unique_code = unique_code self.donor = donor @classmethod def find_by_mod_email(cls, invitee_email: str) -> 'InvitesModel': return cls.query.filter_by(invitee_email=invitee_email).first() def save_to_db(self) -> None: '''Add invite details to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes invite details from the database.''' db.session.delete(self) db.session.commit()
class CategoryModel(db.Model): # Specifying table __tablename__ = "category" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text()) section = db.relationship('SectionModel', secondary=category_section, backref=db.backref('category', lazy='dynamic')) def save_to_db(self) -> None: '''Add category to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes category from the database.''' db.session.delete(self) db.session.commit()
class SectionModel(db.Model): # Specifying table __tablename__ = "section" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(64), unique=True) videos = db.relationship( "VideoModel", secondary=section_video, backref=db.backref("sections", lazy="dynamic"), ) def init(self, title): self.title = title def save_to_db(self) -> None: """Add section to database""" db.session.add(self) db.session.commit() def delete_from_db(self) -> None: """Deletes section from the database.""" db.session.delete(self) db.session.commit() def update(self, **kwargs) -> None: """Updates section""" for field, field_value in kwargs.items(): if hasattr(self, field): setattr(self, field, field_value) db.session.commit() return self def add_video(self, video: "VideoModel") -> None: self.videos.append(video) db.session.add(self) db.session.commit()
class DocumentsModel(db.Model): # Specifying table __tablename__ = "documents" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) application_id = db.Column(db.Integer, db.ForeignKey("application.id")) application = db.relationship( ApplicationModel, backref="documents", primaryjoin="DocumentsModel.application_id == ApplicationModel.id", ) offer_letter = db.Column(db.Text()) fee_structure = db.Column(db.Text()) bank_statement = db.Column(db.Text()) affiliation_letter = db.Column(db.Text()) scholarship_letter = db.Column(db.Text()) additional_doc1 = db.Column(db.Text()) additional_doc2 = db.Column(db.Text()) additional_doc3 = db.Column(db.Text()) def __init__(self, offer_letter, fee_structure, bank_statement): self.offer_letter = offer_letter self.fee_structure = fee_structure self.bank_statement = bank_statement def save_to_db(self) -> None: '''Add document details to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes document details from the database.''' db.session.delete(self) db.session.commit()
class HistoryModel(db.Model): # Specifying table __tablename__ = "history" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) donor_id = db.Column(db.Integer, db.ForeignKey("user.id")) donor = db.relationship( UserModel, backref="history", primaryjoin="HistoryModel.donor_id == UserModel.id", ) recipient_id = db.Column(db.Integer, db.ForeignKey("user.id")) recipient = db.relationship( UserModel, backref="history", primaryjoin="HistoryModel.recipient_id == UserModel.id", ) application_id = db.Column(db.Integer, db.ForeignKey("application.id")) application = db.relationship( ApplicationModel, backref="history", primaryjoin="HistoryModel.application_id == ApplicationModel.id", ) institution_id = db.Column(db.Integer, db.ForeignKey("institution.id")) institution = db.relationship( InstitutionModel, backref="history", primaryjoin="HistoryModel.institution_id == InstitutionModel.id", ) amount = db.Column(db.String(15)) def save_to_db(self) -> None: '''Add history to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes history from the database.''' db.session.delete(self) db.session.commit()
class PreferredLocationModel(db.Model): # Specifying table __tablename__ = "preferred_location" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("user.id")) user = db.relationship( UserModel, backref=db.backref('preferred_location', uselist=False), primaryjoin="PreferredLocationModel.user_id == UserModel.id", ) state = db.Column(db.String(50)) district = db.Column(db.String(50)) sub_district = db.Column(db.String(50)) area = db.Column(db.String(50)) def __init__(self, user_id, state, district, sub_district, area): self.user_id = user_id self.state = state self.district = district self.sub_district = sub_district self.area = area def json(self): '''Preferred Location object in json format.''' return { "state": self.state, "district": self.district, "sub_district": self.sub_district, "area": self.area } @classmethod def find_by_user_id(cls, _user_id: int) -> 'PreferredLocationModel': '''Returns user preferred location of given user id.''' return cls.query.filter_by(user_id=_user_id).first() def save_to_db(self) -> None: """Saves the model to the database.""" db.session.add(self) db.session.commit()
class VideoModel(db.Model): # Specifying table __tablename__ = "videos" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text()) url = db.Column(db.Text(), unique=True) preview_url = db.Column(db.Text()) title = db.Column(db.String(200)) date_published = db.Column(db.Date) source = db.Column(db.String(50), default="Youtube") channel = db.Column(db.String(100)) duration = db.Column(db.Integer) archived = db.Column(db.Boolean) free_to_reuse = db.Column(db.Boolean) authorized_to_reuse = db.Column(db.Boolean) def json(self): '''Returns VideoModel object in json format.''' return { "id": self.id, "name": self.name, "url": self.url, "preview_url": self.preview_url, "title": self.title, "date_published": datetime.strftime(self.date_published, '%Y-%m-%d'), "source": self.source, "channel": self.channel, "duration": self.duration, "archived": self.archived, "free_to_reuse": self.free_to_reuse, "authorized_to_reuse": self.authorized_to_reuse } def find_by_id(cls, _id: int) -> 'VideoModel': '''Returns a particular video of given id.''' return cls.query.filter_by(id=_id).first() def save_to_db(self) -> None: '''Add video to database''' db.session.add(self) db.session.commit() def update(self, new_data: Dict[str, object]) -> None: """Update existing video with new data""" for field in new_data: if hasattr(self, field): setattr(self, field, new_data[field]) db.session.commit() def delete_from_db(self) -> None: '''Deletes video from the database.''' db.session.delete(self) db.session.commit() # authors association def add_authors(self, authors: List['AuthorModel']) -> None: """ Add video authors entities to associated m2m model. :param authors: list of authors to add :return: None """ self.authors.extend(authors) db.session.commit() def update_authors(self, authors: List['AuthorModel']) -> None: """ Replace authors of video -> m2m records :param authors: list of new authors :return: None """ self.authors = authors db.session.commit() def remove_all_authors(self): """ Remove all authors of video (clean m2m records) :return: None """ self.authors = [] db.session.commit() # authors association def add_sections(self, sections: List['SectionModel']) -> None: """ Add video sections entities to associated m2m model. :param sections: list of sections to add :return: None """ self.sections.extend(sections) db.session.commit() def update_sections(self, sections: List['SectionModel']) -> None: """ Replace sections of video -> m2m records :param sections: list of new sections :return: None """ self.sections = sections db.session.commit() def remove_all_sections(self): """ Remove all sections of video (clean m2m records) :return: None """ self.sections = [] db.session.commit()
from app.database.sqlalchemy_extension import db section_video = db.Table( "section_video", db.Column("video_id", db.Integer, db.ForeignKey("videos.id")), db.Column("section_id", db.Integer, db.ForeignKey("section.id")), )
class UserModel(db.Model): """Defines attributes for the user. Attributes: name: A string for storing the user's name. username: A string for storing the user's username. password: A string for storing the user's password. email: A string for storing user email. terms_and_conditions_checked: A boolean indicating if user has agreed to terms and conditions or not. """ # Specifying database table used for UserModel __tablename__ = "users" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) # personal data name = db.Column(db.String(30)) username = db.Column(db.String(30), unique=True) email = db.Column(db.String(254), unique=True) # security password_hash = db.Column(db.String(100)) # registration registration_date = db.Column(db.Float) terms_and_conditions_checked = db.Column(db.Boolean) # admin is_admin = db.Column(db.Boolean) # email verification is_email_verified = db.Column(db.Boolean) email_verification_date = db.Column(db.DateTime) # other info current_mentorship_role = db.Column(db.Integer) membership_status = db.Column(db.Integer) bio = db.Column(db.String(500)) location = db.Column(db.String(80)) occupation = db.Column(db.String(80)) organization = db.Column(db.String(80)) slack_username = db.Column(db.String(80)) social_media_links = db.Column(db.String(500)) skills = db.Column(db.String(500)) interests = db.Column(db.String(200)) resume_url = db.Column(db.String(200)) photo_url = db.Column(db.String(200)) need_mentoring = db.Column(db.Boolean) available_to_mentor = db.Column(db.Boolean) def __init__(self, name, username, password, email, terms_and_conditions_checked): """Initialises userModel class with name, username, password, email, and terms_and_conditions_checked. """ ## required fields self.name = name self.username = username self.email = email self.terms_and_conditions_checked = terms_and_conditions_checked # saving hash instead of saving password in plain text self.set_password(password) # default values self.is_admin = True if self.is_empty( ) else False # first user is admin self.is_email_verified = False self.registration_date = time.time() ## optional fields self.need_mentoring = False self.available_to_mentor = False def json(self): """Returns Usermodel object in json format.""" return { "id": self.id, "name": self.name, "username": self.username, "password_hash": self.password_hash, "email": self.email, "terms_and_conditions_checked": self.terms_and_conditions_checked, "registration_date": self.registration_date, "is_admin": self.is_admin, "is_email_verified": self.is_email_verified, "email_verification_date": self.email_verification_date, "current_mentorship_role": self.current_mentorship_role, "membership_status": self.membership_status, "bio": self.bio, "location": self.location, "occupation": self.occupation, "organization": self.organization, "slack_username": self.slack_username, "social_media_links": self.social_media_links, "skills": self.skills, "interests": self.interests, "resume_url": self.resume_url, "photo_url": self.photo_url, "need_mentoring": self.need_mentoring, "available_to_mentor": self.available_to_mentor, } def __repr__(self): """Returns the user's name and username. """ return f"User name {self.name} . Username is {self.username} ." @classmethod def find_by_username(cls, username: str) -> 'UserModel': """Returns the user that has the username we searched for. """ return cls.query.filter_by(username=username).first() @classmethod def find_by_email(cls, email: str) -> 'UserModel': """Returns the user that has the email we searched for. """ return cls.query.filter_by(email=email).first() @classmethod def find_by_id(cls, _id: int) -> 'UserModel': """Returns the user that has the id we searched for. """ return cls.query.filter_by(id=_id).first() @classmethod def get_all_admins(cls, is_admin=True): """Returns all the admins. """ return cls.query.filter_by(is_admin=is_admin).all() @classmethod def is_empty(cls) -> bool: """Returns a boolean if the Usermodel is empty or not. """ return cls.query.first() is None def set_password(self, password_plain_text: str) -> None: """Sets user password when they create an account or when they are changing their password. """ self.password_hash = generate_password_hash(password_plain_text) # checks if password is the same, using its hash def check_password(self, password_plain_text: str) -> bool: """Returns a boolean if password is the same as it hash or not. """ return check_password_hash(self.password_hash, password_plain_text) def save_to_db(self) -> None: """Adds a user to the database. """ db.session.add(self) db.session.commit() def delete_from_db(self) -> None: """Deletes a user from the database. """ db.session.delete(self) db.session.commit()
from app.database.sqlalchemy_extension import db category_section = db.Table('category_section', db.Column('category_id', db.Integer, db.ForeignKey('category.id')), db.Column('section_id', db.Integer, db.ForeignKey('section.id')) )
from app.database.sqlalchemy_extension import db section_video = db.Table('section_video', db.Column('video_id', db.Integer, db.ForeignKey('videos.id')), db.Column('section_id', db.Integer, db.ForeignKey('section.id')) )
class UserModel(db.Model): # Specifying table __tablename__ = "users" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30)) username = db.Column(db.String(30)) email = db.Column(db.String(100)) firebase_id = db.Column(db.String(50)) password_hash = db.Column(db.String(100)) registration_date = db.Column(db.Integer) terms_and_conditions_checked = db.Column(db.Boolean) access_rights = db.Column(db.Integer) is_email_verified = db.Column(db.Boolean) email_verification_date = db.Column(db.Integer) def __init__(self, name, firebase_id, username, email, password, terms_and_conditions_checked): self.name = name self.username = username self.email = email self.set_password(password) self.registration_date = str(date.today()) self.terms_and_conditions_checked = terms_and_conditions_checked self.access_rights = 0 self.firebase_id = firebase_id def json(self): '''Returns UserModel object in json format.''' return { "id": self.id, "name": self.name, "username": self.username, "email": self.email, "firebase_id": self.firebase_id, "password_hash": self.password_hash, "registration_date": self.registration_date, "terms_and_conditions_checked": self.terms_and_conditions_checked, "access_rights": 0, # access_rights will have to be given by admin "is_email_verified": is_email_verified, "email_verification_date": email_verification_date, } @classmethod def find_by_id(cls, _id: int) -> 'UserModel': '''Returns a particular user of given id.''' return cls.query.filter_by(id=_id).first() @classmethod def find_by_username(cls, username: str) -> 'UserModel': '''Returns a particular user of given username.''' return cls.query.filter_by(username=username).first() @classmethod def find_by_firebase_id(cls, firebase_id: str) -> 'UserModel': '''Returns user of given firebase_id.''' return cls.query.filter_by(firebase_id=firebase_id).first() @classmethod def find_by_email(cls, email: str) -> 'UserModel': '''Returns user of given email.''' return cls.query.filter_by(email=email).first() def set_password(self, password_plain_text: str) -> None: """Sets user password""" self.password_hash = generate_password_hash(password_plain_text) def save_to_db(self) -> None: '''Add user to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes user from the database.''' db.session.delete(self) db.session.commit()
from app.database.sqlalchemy_extension import db category_section = db.Table( "category_section", db.Column("category_id", db.Integer, db.ForeignKey("category.id")), db.Column("section_id", db.Integer, db.ForeignKey("section.id")), )
from app.database.sqlalchemy_extension import db application_moderator = db.Table( 'application_moderator', db.Column('application_id', db.Integer, db.ForeignKey('application.id')), db.Column('moderator_id', db.Integer, db.ForeignKey('user.id')))
class UserModel(db.Model): # Specifying table __tablename__ = "user" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) firebase_id = db.Column(db.String(100)) name = db.Column(db.String(70)) email = db.Column(db.String(100)) password_hash = db.Column(db.String(100)) is_email_verified = db.Column(db.Boolean) profile_image = db.Column(db.Text()) occupation = db.Column(db.Text()) is_donor = db.Column(db.Boolean) is_recipient = db.Column(db.Boolean) is_moderator = db.Column(db.Boolean) address = db.Column(db.Text()) location = db.Column(db.Text()) def __init__(self, firebase_id, name, email, password, role): self.name = name self.email = email self.firebase_id = firebase_id # saving hash of password self.set_password(password) # Setting role of a user if role == 0: self.is_donor = True self.is_recipient = False self.is_moderator = False elif role == 1: self.is_donor = False self.is_recipient = True self.is_moderator = False elif role == 2: self.is_donor = False self.is_recipient = False self.is_moderator = True self.is_email_verified = False def json(self): '''UserModel object in json format.''' return { "id": self.id, "firebase_id": self.firebase_id, "name": self.name, "email": self.email, "is_email_verified": self.is_email_verified, "profile_image": self.profile_image, "address": self.address, "location": self.location, "occupation": self.occupation, "is_donor": self.is_donor, "is_recipient": self.is_recipient, "is_moderator": self.is_moderator, "profile_image": self.profile_image } @classmethod def find_by_email(cls, email: str) -> 'UserModel': return cls.query.filter_by(email=email).first() @classmethod def find_by_id(cls, _id: int) -> 'UserModel': '''Returns user of given id.''' return cls.query.filter_by(id=_id).first() @classmethod def find_by_firebase_id(cls, firebase_id: str) -> 'UserModel': '''Returns user of given firebase_id.''' return cls.query.filter_by(firebase_id=firebase_id).first() def set_password(self, password_plain_text: str) -> None: """Sets user password""" self.password_hash = generate_password_hash(password_plain_text) def check_password(self, password_plain_text: str) -> bool: """Returns a boolean if password is the same as it's hash.""" return check_password_hash(self.password_hash, password_plain_text) def save_to_db(self) -> None: '''Add user to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes user from the database.''' db.session.delete(self) db.session.commit()
class VideoModel(db.Model): # Specifying table __tablename__ = "videos" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text()) url = db.Column(db.Text()) title = db.Column(db.String(200)) published = db.Column(db.Integer) source = db.Column(db.String(50)) channel = db.Column(db.String(100)) duration = db.Column(db.Integer) archived = db.Column(db.Boolean) free_to_reuse = db.Column(db.Boolean) authorised_to_reuse = db.Column(db.Boolean) def json(self): '''Returns VideoModel object in json format.''' return { "id": self.id, "name": self.name, "url": self.url, "title": self.title, "published": self.published, "source": self.source, "channel": self.channel, "duration": self.duration, "archived": self.archived, "free_to_reuse": self.free_to_reuse, "authorised_to_reuse": self.authorised_to_reuse } def find_by_id(cls, _id: int) -> 'VideoModel': '''Returns a particular video of given id.''' return cls.query.filter_by(id=_id).first() def save_to_db(self) -> None: '''Add video to database''' db.session.add(self) db.session.commit() def delete_from_db(self) -> None: '''Deletes video from the database.''' db.session.delete(self) db.session.commit()
from app.database.sqlalchemy_extension import db video_author = db.Table('video_author', db.Column('author_id', db.Integer, db.ForeignKey('author.id')), db.Column('video_id', db.Integer, db.ForeignKey('videos.id')) )
class TaskCommentModel(db.Model): """Defines attributes for the task comment. Attributes: task_id: An integer for storing the task's id. user_id: An integer for storing the user's id. relation_id: An integer for storing the relation's id. creation_date: A float indicating comment's creation date. modification_date: A float indicating the modification date. comment: A string indicating the comment. """ # Specifying database table used for TaskCommentModel __tablename__ = "tasks_comments" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) task_id = db.Column(db.Integer, db.ForeignKey("tasks_list.id")) relation_id = db.Column(db.Integer, db.ForeignKey("mentorship_relations.id")) creation_date = db.Column(db.Float, nullable=False) modification_date = db.Column(db.Float) comment = db.Column(db.String(COMMENT_MAX_LENGTH), nullable=False) def __init__(self, user_id, task_id, relation_id, comment): # required fields self.user_id = user_id self.task_id = task_id self.relation_id = relation_id self.comment = comment # default fields self.creation_date = datetime.now().timestamp() def json(self): """Returns information of task comment as a JSON object.""" return { "id": self.id, "user_id": self.user_id, "task_id": self.task_id, "relation_id": self.relation_id, "creation_date": self.creation_date, "modification_date": self.modification_date, "comment": self.comment, } def __repr__(self): """Returns the task and user ids, creation date and the comment.""" return (f"User's id is {self.user_id}. Task's id is {self.task_id}. " f"Comment was created on: {self.creation_date}\n" f"Comment: {self.comment}") @classmethod def find_by_id(cls, _id): """Returns the task comment that has the passed id. Args: _id: The id of the task comment. """ return cls.query.filter_by(id=_id).first() @classmethod def find_all_by_task_id(cls, task_id, relation_id): """Returns all task comments that has the passed task id. Args: task_id: The id of the task. relation_id: The id of the relation. """ return cls.query.filter_by(task_id=task_id, relation_id=relation_id).all() @classmethod def find_all_by_user_id(cls, user_id): """Returns all task comments that has the passed user id. Args: user_id: The id of the user. """ return cls.query.filter_by(user_id=user_id).all() def modify_comment(self, comment): """Changes the comment and the modification date. Args: comment: New comment. """ self.comment = comment self.modification_date = datetime.now().timestamp() @classmethod def is_empty(cls): """Returns a boolean if the TaskCommentModel is empty or not.""" return cls.query.first() is None def save_to_db(self): """Adds a comment task to the database.""" db.session.add(self) db.session.commit() def delete_from_db(self): """Deletes a comment task from the database.""" db.session.delete(self) db.session.commit()
class MentorshipRelationModel(db.Model): """Data Model representation of a mentorship relation. Attributes: id: integer primary key that defines the mentorships. mentor_id: integer indicates the id of the mentor. mentee_id: integer indicates the id of the mentee. action_user_id: integer indicates id of action user. mentor: relationship between UserModel and mentorship_relation. mentee: relationship between UserModel and mentorship_relation. creation_date: float that defines the date of creation of the mentorship. accept_date: float that indicates the date of acceptance of mentorship. start_date: float that indicates the starting date of mentorship. end_date: float that indicates the ending date of mentorship. state: enumeration that indicates state of mentorship. notes: string that indicates any notes. tasks_list_id: integer indicates the id of the tasks_list tasks_list: relationship between TasksListModel and mentorship_relation. """ # Specifying database table used for MentorshipRelationModel __tablename__ = "mentorship_relations" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) # personal data mentor_id = db.Column(db.Integer, db.ForeignKey("users.id")) mentee_id = db.Column(db.Integer, db.ForeignKey("users.id")) action_user_id = db.Column(db.Integer, nullable=False) mentor = db.relationship( UserModel, backref="mentor_relations", primaryjoin="MentorshipRelationModel.mentor_id == UserModel.id", ) mentee = db.relationship( UserModel, backref="mentee_relations", primaryjoin="MentorshipRelationModel.mentee_id == UserModel.id", ) creation_date = db.Column(db.Float, nullable=False) accept_date = db.Column(db.Float) start_date = db.Column(db.Float) end_date = db.Column(db.Float) state = db.Column(db.Enum(MentorshipRelationState), nullable=False) notes = db.Column(db.String(400)) tasks_list_id = db.Column(db.Integer, db.ForeignKey("tasks_list.id")) tasks_list = db.relationship(TasksListModel, uselist=False, backref="mentorship_relation") def __init__( self, action_user_id, mentor_user, mentee_user, creation_date, end_date, state, notes, tasks_list, ): self.action_user_id = action_user_id self.mentor = mentor_user self.mentee = mentee_user # same as mentee_user.mentee_relations.append(self) self.creation_date = creation_date self.end_date = end_date self.state = state self.notes = notes self.tasks_list = tasks_list def json(self): """Returns information of mentorship as a json object.""" return { "id": self.id, "action_user_id": self.action_user_id, "mentor_id": self.mentor_id, "mentee_id": self.mentee_id, "creation_date": self.creation_date, "accept_date": self.accept_date, "start_date": self.start_date, "end_date": self.end_date, "state": self.state, "notes": self.notes, } # def __repr__(self): # return f"Mentorship Relation with id = {self.id}, Mentor has id = {self.mentor_id} and Mentee has id = {self.mentee_id}" @classmethod def find_by_id(cls, _id) -> 'MentorshipRelationModel': """Returns the mentorship that has the passed id. Args: _id: The id of a mentorship. """ return cls.query.filter_by(id=_id).first() @classmethod def is_empty(cls) -> bool: """Returns True if the mentorship model is empty, and False otherwise.""" return cls.query.first() is None def save_to_db(self) -> None: """Saves the model to the database.""" db.session.add(self) db.session.commit() def delete_from_db(self) -> None: """Deletes the record of mentorship relation from the database.""" self.tasks_list.delete_from_db() db.session.delete(self) db.session.commit()