class Posts(db.Model): id = db.Column(db.Integer, primary_key=True) deleted = db.Column(db.Boolean, default=False) deleted_at = db.Column(db.DateTime, default=None) created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) title = db.Column(db.String(200), nullable=False) thumbnail = db.Column(db.Text) slug = db.Column(db.String(200), nullable=False, unique=True) brief = db.Column(db.Text, nullable=False) content = db.Column(db.Text, nullable=False) last_edited_at = db.Column(db.DateTime) user = db.relationship('Users', backref=db.backref('posts', lazy=True)) votes = db.relationship("Votes", back_populates="post") tags = db.relationship('Tags', secondary=post_tags, lazy='subquery', backref=db.backref('posts', lazy=True)) def __repr__(self): return '<Posts %r>' % self.title
class Creator(db.Model): __tablename__ = 'creator' id = db.Column(db.Integer(), primary_key=True) firstName = db.Column(db.String(100)) middleName = db.Column(db.String(100)) lastName = db.Column(db.String(100)) suffix = db.Column(db.String(100)) fullName = db.Column(db.String(100)) modified = db.Column(db.DateTime()) comics = db.relationship(Comics, secondary=creator_comics, backref=db.backref('creators', lazy=True)) def __init__(self, id, firstName, middleName, lastName, suffix, fullName, modified, comics): self.id = id self.firstName = firstName self.middleName = middleName self.lastName = lastName self.suffix = suffix self.fullName = fullName self.modified = modified self.comics = comics def create(self): db.session.add(self) db.session.commit() return self
class Comments(db.Model): id = db.Column(db.Integer, primary_key=True) deleted = db.Column(db.Boolean, default=False) deleted_at = db.Column(db.DateTime, default=None) created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable=False) content = db.Column(db.Text, nullable=False) post = db.relationship('Posts', backref=db.backref('comments', lazy=True)) user = db.relationship('Users', backref=db.backref('comments', lazy=True)) def __repr__(self): return '<Comment %r>' % self.content
class StudyClass(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(10), unique=True, nullable=False) year_of_study = db.Column(db.String(2), unique=False, nullable=False) schedule_id = db.Column(db.Integer, db.ForeignKey('schedule.id')) professor_id = db.Column(db.Integer, db.ForeignKey('professor.id')) schedule = db.relationship('Schedule', backref=db.backref('classes', lazy=True)) discipline = db.relationship('Discipline', backref='study_class') def __repr__(self): return f'{self.name} {self.year_of_study}'
class Votes(db.Model): id = db.Column(db.Integer, primary_key=True) deleted = db.Column(db.Boolean, default=False) deleted_at = db.Column(db.DateTime, default=None) created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow) vote = db.Column(db.Boolean, default=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable=False) post = db.relationship("Posts", uselist=False, back_populates="votes") user = db.relationship('Users', backref=db.backref('votes', lazy=True)) def __repr__(self): return '<Vote %r>' % self.vote
class Student(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), unique=False, nullable=False) surname = db.Column(db.String(30), unique=False, nullable=False) address = db.Column(db.String(200), unique=False, nullable=True) year_of_study = db.Column(db.String(2), unique=False, nullable=True) adm_score = db.Column(db.Float, unique=False, nullable=False) # Current exam scores for all past years and semesters scores = db.Column(db.String(200), unique=False, nullable=True) # Foreign key to a StudyClass instance study_class_id = db.Column(db.Integer, db.ForeignKey('study_class.id')) # Foreign key relationship study_class = db.relationship('StudyClass', backref=db.backref('students', lazy=True)) def __repr__(self): return f'{self.name} {self.surname} {self.address} {self.adm_score} {self.scores}'
class User(UserMixin, db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey("roles.id")) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) housemates = db.Column(db.Text()) significant_others = db.Column(db.Text()) my_five = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship("Post", backref="author", lazy="dynamic") followed = db.relationship( "Follow", foreign_keys=[Follow.follower_id], backref=db.backref(name="follower", lazy="joined"), lazy="dynamic", cascade="all, delete-orphan", ) followers = db.relationship( "Follow", foreign_keys=[Follow.followed_id], backref=db.backref(name="followed", lazy="joined"), lazy="dynamic", cascade="all, delete-orphan", ) @staticmethod def add_self_follows(): # this is used as a script to go back and add self follows if they are missing for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if not self.role: if self.email == current_app.config["MYQ5_ADMIN"]: self.role = Role.query.filter_by(name="Administrator").first() if not self.role: self.role = Role.query.filter_by(default=True).first() if not self.email and not self.avatar_hash: self.avatar_hash = self.gravatar_hash() self.follow(self) @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id).filter( Follow.follower_id == self.id) @property def followed_users(self): return User.query.join(Follow, Follow.followed_id == User.id).filter( Follow.follower_id == 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) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config["SECRET_KEY"], expiration) return s.dumps({"confirm": self.id}).decode("utf-8") def confirm(self, token): s = Serializer(current_app.config["SECRET_KEY"]) try: data = s.loads(token.encode("utf-8")) except Exception: return False if data.get("confirm") != self.id: return False self.confirmed = True db.session.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config["SECRET_KEY"], expiration) return s.dumps({"reset": self.id}).decode("utf-8") @staticmethod def reset_password(token, new_password): s = Serializer(current_app.config["SECRET_KEY"]) try: data = s.loads(token.encode("utf-8")) except: return False user = User.query.get(data.get("reset")) if user is None: return False user.password = new_password db.session.add(user) return True def generate_email_change_token(self, new_email, expiration=3600): s = Serializer(current_app.config["SECRET_KEY"], expiration) return s.dumps({ "change_email": self.id, "new_email": new_email }).decode("utf-8") def change_email(self, token): s = Serializer(current_app.config["SECRET_KEY"]) try: data = s.loads(token.encode("utf-8")) except: return False if data.get("change_email") != self.id: return False new_email = data.get("new_email") self.avatar_hash = self.gravatar_hash() if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email db.session.add(self) return True def can(self, perm): return self.role is not None and self.role.has_permission(perm) def is_administrator(self): return self.can(Permission.ADMIN) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def gravatar_hash(self): return hashlib.md5(self.email.lower().encode("utf-8")).hexdigest() def gravatar(self, size=100, default="identicon", rating="g"): url = "https://secure.gravatar.com/avatar" gravatar_hash = self.avatar_hash or self.gravatar_hash() return f"{url}/{gravatar_hash}?s={size}&d={default}&r={rating}" def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): if user.id is None: return False return self.followed.filter_by(followed_id=user.id).first() is not None def is_followed_by(self, user): if user.id is None: return False return self.followers.filter_by( follower_id=user.id).first() is not None def __repr__(self): return f"<User {self.username}>"
class CommunityModel(db.Model): __tablename__ = 'communities' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(120), nullable=False) time_created = db.Column(db.DateTime(), default=datetime.datetime.utcnow) time_updated = db.Column(db.DateTime(), onupdate=datetime.datetime.utcnow) users = db.relationship( 'UserModel', secondary='community_user_link', secondaryjoin='and_(CommunityUserLinkModel.user_id == UserModel.id, ' 'CommunityUserLinkModel.invitation_accepted == True)') car_id = db.Column(db.Integer, db.ForeignKey('cars.id'), unique=True) car = db.relationship("CarModel", backref=db.backref("community", uselist=False)) is_favourite = None def persist(self): db.session.add(self) db.session.commit() @staticmethod def get_marshaller(): return { 'id': fields.Integer, 'name': fields.String, 'time_created': fields.DateTime, 'time_updated': fields.DateTime, 'users': fields.List(fields.Nested(UserModel.get_marshaller())), 'car': fields.Nested(CarModel.get_marshaller()) } @staticmethod def get_detailed_marshaller(): return { 'id': fields.Integer, 'name': fields.String, 'time_created': fields.DateTime, 'time_updated': fields.DateTime, 'users': fields.List(fields.Nested(UserModel.get_marshaller())), 'car': fields.Nested(CarModel.get_marshaller()), 'is_deletable': fields.Boolean, 'is_editable': fields.Boolean } @staticmethod def add_is_fav_to_marshaller(marshaller): marshaller['is_favourite'] = fields.Boolean return marshaller @classmethod def find_by_car_id(cls, id): return cls.query.filter_by(car_id=id).first() @classmethod def find_by_id(cls, id): return cls.query.filter_by(id=id).first() @classmethod def return_all(cls): return CommunityModel.query.all() @classmethod def delete_all(cls): db.session.query(cls).delete() db.session.commit() @classmethod def delete_by_id(cls, id): community = db.session.query(cls).filter(cls.id == id).first() if community: db.session.delete(community) db.session.commit() else: raise NoData