class Ban(db.Model): __tablename__ = 'ban' ban_id = db.Column(db.Integer, primary_key=True) banned_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False) banner_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False) report_id = db.Column(db.Integer, db.ForeignKey('report.report_id'), nullable=False) ban_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) active = db.Column(db.Integer, default=1) def __init__(self, banned_id, banner_id, report_id, active): self.banned_id = banned_id self.banner_id = banner_id self.report_id = report_id self.active = active @classmethod def getBannedStatus(self, user_id): query = self.query.filter(Ban.banned_id == user_id).all() for ban in query: if ban.active: return 1 else: return 0 @classmethod def getAll(self): return self.query.filter(Ban.active).all() @classmethod def getBanById(self, ban_id): return self.query.filter(Ban.ban_id == ban_id).first()
class ReportHasReason(db.Model): __tablename__ = 'report_has_reason' report_id = db.Column(db.Integer, db.ForeignKey('report.report_id'), nullable=False, primary_key=True) reason_id = db.Column(db.Integer, db.ForeignKey('report_reason.reason_id'), nullable=False, primary_key=True) def __init__(self, report_id, reason_id): self.report_id = report_id self.reason_id = reason_id @classmethod def getReasonsForReport(self, report_id): query = self.query.filter(ReportHasReason.report_id == report_id).all() reasons = [] for reportReason in query: reasons.append(reportReason.reason_id) return reasons
class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) content = db.Column(db.Text, nullable=False) upvote = db.Column(db.Integer, nullable=False, default=0) upvoters = db.relationship('CommentUpvote', backref='comment', lazy='dynamic') downvoters = db.relationship('CommentDownvote', backref='comment', lazy='dynamic') downvote = db.Column(db.Integer, nullable=False, default=0) modified_on = db.Column( db.DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now(), ) link_id = db.Column(db.Integer, db.ForeignKey('links.id'), nullable=True) text_id = db.Column(db.Integer, db.ForeignKey('texts.id'), nullable=True) comment_id = db.Column(db.Integer, db.ForeignKey('comments.id'), nullable=True) children = db.relationship('Comment', backref=db.backref('parent', remote_side=[id]), lazy='dynamic') def __repr__(self): return f"{self.content} | {self.id}" def get_score(self): """Get score of a comment""" return self.upvote - self.downvote def save(self): db.session.add(self) db.session.commit() CommentUpvote(user_id=self.user_id, comment_id=self.id).save()
class ThreadDownvote(db.Model): __tablename__ = 'thread_downvotes' id = db.Column(db.Integer, primary_key=True) link_id = db.Column(db.Integer, db.ForeignKey('links.id'), nullable=True) text_id = db.Column(db.Integer, db.ForeignKey('texts.id'), nullable=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) def save(self): db.session.add(self) # retrieve user to update karma if self.link_id: link = Link.query.get(self.link_id) _id = link.user_id link.downvote += 1 else: text = Text.query.get(self.text_id) _id = text.user_id text.downvote += 1 user = User.query.get(_id) user.post_karma -= 1 db.session.commit()
class User(db.Model): __tablename__ = 'user' user_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20)) email = db.Column(db.String(20)) password_hash = db.Column(db.String(20)) token = db.Column(db.String(20)) is_admin = db.Column(db.Integer) date_joined = db.Column(db.DateTime, default=datetime.utcnow) avatar_id = db.Column(db.Integer) def __init__(self, name, email, password_hash, token, is_admin, avatar_id): self.name = name self.email = email self.password_hash = password_hash self.token = token self.is_admin = is_admin self.avatar_id = avatar_id @classmethod def getAll(self): return self.query.all() @classmethod def getUserById(self, user_id): return self.query.get(user_id) @classmethod def getUserByToken(self, token): return self.query.filter(User.token == token).first() @classmethod def getUserByEmail(self, email): return self.query.filter(User.email == email).first() @classmethod def getEmail(self): return self._email def get_id(self): try: return text_type(self.uid) except AttributeError: raise NotImplementedError('No `id` attribute - override `get_id`')
class Activity(db.Model): activity_id = db.Column(db.Integer, primary_key=True) comment = db.Column(db.String(250), nullable=True) upvote = db.Column(db.Boolean, default=False) downvote = db.Column(db.Boolean, default=False) id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('post.post_id'), nullable=False) date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) def __repr__(self): return f"Activity('{self.activity_id}','{self.post_id},'{self.comment}','{self.upvote}','{self.downvote}','{self.date_created}')"
class Post(db.Model): post_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) body = db.Column(db.String(250), nullable=False) image = db.Column(db.String(100), nullable=True, default='default.jpg') id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) activities = db.relationship('Activity', backref='post', lazy=True) def __repr__(self): return f"Post('{self.post_id}','{self.title}','{self.body}','{self.image}','{self.id}')"
class Post(db.Model): __tablename__ = 'post' post_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) post_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) poster_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey('category.category_id'), nullable=False) def __init__(self, title, content, poster_id, category_id): self.title = title self.content = content self.poster_id = poster_id self.category_id = category_id @classmethod def getPostsByUser(self, user_id): return self.query.filter(Post.poster_id == user_id).all() @classmethod def getPostById(self, post_id): return self.query.filter(Post.post_id == post_id).first() @classmethod def getAll(self): return self.query.all() @classmethod def getPostsWithContentContaining(self, keyword): return self.query.filter(Post.content.like('%' + keyword + '%')).all() @classmethod def getPostsContaining(self, keyword): return self.query.filter( Post.title.like('%' + keyword + '%') | Post.content.like('%' + keyword + '%')).all() @classmethod def getPostCountByCategoryId(self, category_id): return self.query.filter(Post.category_id == category_id).count()
class Post(db.Model): __tablename__ = 'posts' pid = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) post_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow()) uid = db.Column(db.Integer, db.ForeignKey('users.uid'), nullable=False) tid = db.Column(db.Integer, db.ForeignKey('topics.tid'), nullable=False) comments = db.relationship("Comment", backref="posts") likes = db.relationship("Like", backref="posts") def __init__(self, title, content, post_time, uid, tid): self.title = title self.content = content self.post_time = post_time self.uid = uid self.tid = tid
class Comment(db.Model): __tablename__ = 'comments' cid = db.Column(db.Integer, primary_key=True) content = db.Column(db.Text, nullable=False) post_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow()) uid = db.Column(db.Integer, db.ForeignKey('users.uid'), nullable=False) pid = db.Column(db.Integer, db.ForeignKey('posts.pid'), nullable=False) father_id = db.Column(db.Integer, db.ForeignKey('comments.cid'), nullable=True) def __init__(self, content, post_time, pid): self.content = content self.post_time = post_time self.pid = pid def get_id(self): try: return text_type(self.cid) except AttributeError: raise NotImplementedError('No `id` attribute - override `get_id`')
class Topic(db.Model): id = db.Column(db.Integer, primary_key = True) header = db.Column(db.String(100), nullable = False) user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable = False) content = db.Column(db.Text, nullable = False) date = db.Column(db.DateTime, default = datetime.utcnow, nullable = False)
class Config(Base): __tablename__ = "config" key = db.Column(db.Text, nullable=False) value = db.Column(db.Text)
class Comment(db.Model): """Model for the Comment object. Attributes ---------- id : int The automatically-generated database id of the comment body : string The body of the comment. HTML is allowed for rich text, but script tags are not to prevent XSS attacks author_id : int The database ID of the user that created the comment author : User The user object associated with the author_id. This is automatically created as a back-reference by SQLAlchemy on insertion and not declared explicitly amongst the class attributes creation_date : datetime The date the Comment instance was created last_updated : datetime The date the Comment instance was last updated Methods ------- to_json() Returns the comment's fields in a JSON serializable format """ id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text, nullable=False) author_id = db.Column( db.Integer, db.ForeignKey('user.id') ) creation_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) last_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow) post_id = db.Column( db.Integer, db.ForeignKey('post.id'), nullable=False ) def to_json(self) -> dict: """Returns the comment's fields in a JSON serializable format. Returns ------- dict The comment's ID as integer, body as string, author as string of just username, creation_date as formatted datetime string, last_updated as formatted datetime string """ author = self.author.username if self.author else 'undefined' return { 'id': self.id, 'body': self.body, 'author': author, 'creation_date': self.creation_date.strftime(TIME_FMT), 'last_updated': self.last_updated.strftime(TIME_FMT), 'parent': self.post_id }
class Alembic(Base): __tablename__ = "alembic_v" version = db.Column(db.Text, nullable=False)
class Post(db.Model): """Model for the Post object. Attributes ---------- id : int The automatically-generated database id of the post title : string The title of the post body : string The body of the post. HTML is allowed for rich text, but script tags are not to prevent XSS attacks author_id : int The database ID of the user that created the post author : User The user object associated with the author_id. This is automatically created as a back-reference by SQLAlchemy on insertion and not declared explicitly amongst the class attributes creation_date : datetime The date the Post instance was created last_updated : datetime The date the Post instance was last updated views : int The number of times the Post was viewed liked_by : list List of user accounts that liked this post Methods ------- to_json() Returns the post's fields in a JSON serializable format """ id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text, nullable=False) body = db.Column(db.Text, nullable=False) author_id = db.Column( db.Integer, db.ForeignKey('user.id') ) creation_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) last_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow) views = db.Column(db.Integer, default=0) liked_by = db.relationship('User', secondary=posts, lazy='subquery', backref=db.backref('liked', lazy=True)) comments = db.relationship('Comment', backref='post', lazy=True) def to_json(self) -> dict: """Returns the post's fields in a JSON serializable format. Returns ------- dict The post's ID as integer, title as string, body as string, author as string of just username, creation_date as formatted datetime string, last_updated as formatted datetime string, views as integer, and liked_by as list of usernames """ author = self.author.username if self.author else 'undefined' return { 'id': self.id, 'title': self.title, 'body': self.body, 'author': author, 'creation_date': self.creation_date.strftime(TIME_FMT), 'last_updated': self.last_updated.strftime(TIME_FMT), 'views': self.views, 'liked_by': [user.username for user in self.liked_by], 'comments': [comment.to_json() for comment in self.comments] }
import datetime from forum import db from forum.constants import TIME_FMT posts = db.Table('posts', db.Column( 'post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True ), db.Column( 'user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True ) ) class Post(db.Model): """Model for the Post object. Attributes ---------- id : int The automatically-generated database id of the post title : string The title of the post body : string The body of the post. HTML is allowed for rich text, but script tags are not to prevent XSS attacks
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) login = db.Column(db.String(128), unique=True, nullable=False) password = db.Column(db.String(255), nullable=False)
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key = True) username = db.Column(db.String(20), unique = True, nullable = False) password = db.Column(db.String(60), nullable = False) topics = db.relationship("Topic", backref = "author", lazy = True)
def subreddit_id(cls): """Foreign key to Subreddit table""" return db.Column(db.Integer, db.ForeignKey('subreddits.id'))
def user_id(cls): """Foreign key to User table""" return db.Column(db.Integer, db.ForeignKey('users.id'))
class User(db.Model): """Model for the User object. Attributes ---------- id : int The automatically-generated database id of the user username : string The chosen visible name of the user account password : string The hashed password for the user of the account creation_date : datetime The date the user instance was created last_updated : datetime The date the user instance was last modified bio : string The user's own description of themselves posts : list The list of posts this user has created Methods ------- to_json() Returns the user's fields in a JSON serializable format """ id = db.Column(db.Integer, primary_key=True) username = db.Column(db.Unicode, nullable=False) password = db.Column(db.Unicode, nullable=False) creation_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) last_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow) bio = db.Column(db.Text) token = db.Column(db.Unicode) posts = db.relationship('Post', backref='author', lazy=True) comments = db.relationship('Comment', backref='author', lazy=True) def __init__(self, *args, **kwargs) -> None: """Overrides the inherited init method to hash incoming passwords.""" kwargs["password"] = hasher.hash(kwargs["password"]) kwargs["token"] = secrets.token_urlsafe(64) super().__init__(*args, **kwargs) def to_json(self) -> dict: """Returns the user's fields in a JSON serializable format. Returns ------- dict The user's ID as integer, username as string, creation_date and last_updated as formatted datetime string, and bio as string. """ return { 'id': self.id, 'username': self.username, 'creation_date': self.creation_date.strftime(TIME_FMT), 'last_updated': self.last_updated.strftime(TIME_FMT), 'bio': self.bio, 'posts': [post.to_json() for post in self.posts] }