class Report(db.Model): __tablename__ = 'report' report_id = db.Column(db.Integer, primary_key=True) reporter_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('post.post_id'), nullable=False) report_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) content = db.Column(db.Text, nullable=False) active = db.Column(db.Integer, default=1) def __init__(self, reporter_id, post_id, content, active): self.reporter_id = reporter_id self.post_id = post_id self.content = content self.active = active @classmethod def getAll(self): return self.query.filter(Report.active).all() @classmethod def getReportById(self, report_id): return self.query.filter(Report.report_id == report_id).first()
class Thread(Base): json_attributes = ("id", "title", "slug", "content", "user_id", "category_id", "comments_count") __tablename__ = "threads" title = db.Column(db.String(100), nullable=False) slug = db.Column(db.String(250), nullable=False) content = db.Column(db.Text) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) category_id = db.Column(db.Integer, db.ForeignKey("categories.id")) views_count = db.Column(db.Integer, nullable=False, default=0) comments_count = db.Column(db.Integer, default=0) best_comment_id = db.Column(db.Integer, nullable=True) owner = db.relationship("User", back_populates="threads") category = db.relationship("Category", back_populates="threads") comments = db.relationship("Comment", back_populates="thread") @property def summary(self): return self.content[0:300] + "..." def is_owner(self, user): return user == self.owner def add_comment(self, content, owner): comment = Comment(content=content, user_id=owner.id, thread_id=self.id) comment.save() return comment @hybrid_property def has_comments(self): return self.comments_count > 0
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 Likes(db.Model): __tablename__ = 'likes' user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False, primary_key=True) post_id = db.Column(db.Integer, db.ForeignKey('post.post_id'), nullable=False, primary_key=True) def __init__(self, user_id, post_id): self.user_id = user_id self.post_id = post_id @classmethod def getLikedPostsByUser(self, user_id): return self.query.filter(Likes.user_id == user_id).all() @classmethod def getPostLikeCount(self, post_id): return self.query.filter(Likes.post_id == post_id).count() @classmethod def getLike(self, user_id, post_id): return self.query.filter(Likes.post_id == post_id).filter( Likes.user_id == user_id).first() @classmethod def userLikedPost(self, user_id, post_id): return self.query.filter(Likes.user_id == user_id).filter( Likes.post_id == post_id).first() != None
class Like(db.Model): __tablename__ = 'likes' lid = db.Column(db.Integer, primary_key=True) uid = db.Column(db.Integer, db.ForeignKey('users.uid'), nullable=False) pid = db.Column(db.Integer, db.ForeignKey('posts.pid'), nullable=False) post_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow()) def __init__(self, uid, pid, post_time): self.uid = uid self.pid = pid self.post_time = post_time
class Comment(Base): __tablename__ = "comments" content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) thread_id = db.Column(db.Integer, db.ForeignKey("threads.id")) owner = db.relationship("User", back_populates="comments") thread = db.relationship("Thread", back_populates="comments") def is_owner(self, user): print(self.user_id, user.id) return self.owner == user
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 Tag(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(32), nullable=False) message_id = db.Column(db.Integer, db.ForeignKey( 'message.id'), nullable=False) message = db.relationship('Message', backref=db.backref('tags', lazy=True))
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 Comment(db.Model): __tablename__ = 'comment' comment_id = 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) commenter_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('post.post_id'), nullable=False) def __init__(self, content, commenter_id, post_id): self.content = content self.commenter_id = commenter_id self.post_id = post_id def get_id(self): try: return text_type(self.cid) except AttributeError: raise NotImplementedError('No `id` attribute - override `get_id`') @classmethod def getComments(self, post_id): return self.query.filter(Comment.post_id == post_id).all() @classmethod def getCommentsContaining(self, keyword): return self.query.filter(Comment.content.like('%' + keyword + '%')).all() @classmethod def getCommentsByUser(self, user_id): return self.query.filter(Comment.commenter_id == user_id).all() @classmethod def getCommentCount(self, post_id): return self.query.filter(Comment.post_id == post_id).count() @classmethod def getUserCommentCount(self, user_id): return self.query.filter(Comment.commenter_id == user_id).count()
class Message(db.Model): __tablename__ = "messages" id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid4) text = db.Column(db.Text()) category_id = db.Column(UUID(as_uuid=True), db.ForeignKey("categories.id")) author_id = db.Column(UUID(as_uuid=True), db.ForeignKey("users.id")) posted_at = db.Column(db.DateTime) category = db.relationship("Category", backref=db.backref("messages", lazy=True)) user = db.relationship("User", backref=db.backref("messages", lazy=True)) def __repl__(self): return "<Message author='%s' posted_at='%s'>" % (self.author_id, self.posted_at) def __str__(self): return self.__repl__()
class CommentDownvote(db.Model): __tablename__ = 'comment_downvotes' id = db.Column(db.Integer, primary_key=True) comment_id = db.Column(db.Integer, db.ForeignKey('comments.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) def save(self): db.session.add(self) # retrieve user to update karma comment = Comment.query.get(self.comment_id) comment.downvote -= 1 user = User.query.get(comment.user_id) user.comment_karma -= 1 db.session.commit()
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' 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 Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.today) content = db.Column(db.Text, nullable=False) userid = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) def __repr__(self): return f"Post({self.title}, {self.date_posted})"
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 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 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 Category(db.Model): __tablename__ = "categories" id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid4) name = db.Column(db.String(), nullable=False) parent_id = db.Column(UUID(as_uuid=True), db.ForeignKey("categories.id")) parent = db.relationship("Category", remote_side=[id]) def __repl__(self): return "<Category id='%s' name='%s'>" % (self.id, self.name) def __str__(self): return self.__repl__()
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 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 }
def user_id(cls): """Foreign key to User table""" return db.Column(db.Integer, db.ForeignKey('users.id'))
def subreddit_id(cls): """Foreign key to Subreddit table""" return db.Column(db.Integer, db.ForeignKey('subreddits.id'))
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 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)