コード例 #1
0
ファイル: model.py プロジェクト: seongminp/ForumApp
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()
コード例 #2
0
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
コード例 #3
0
ファイル: model.py プロジェクト: seongminp/ForumApp
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()
コード例 #4
0
ファイル: model.py プロジェクト: seongminp/ForumApp
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
コード例 #5
0
ファイル: model.py プロジェクト: Sean858/ForumApp
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
コード例 #6
0
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
コード例 #7
0
ファイル: models.py プロジェクト: 2011-01065/flask-finals
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}')"
コード例 #8
0
ファイル: models.py プロジェクト: IvanPostu/python-flask
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))
コード例 #9
0
ファイル: model.py プロジェクト: seongminp/ForumApp
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()
コード例 #10
0
ファイル: model.py プロジェクト: seongminp/ForumApp
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()
コード例 #11
0
ファイル: model.py プロジェクト: LliriKnat/Forum
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__()
コード例 #12
0
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()
コード例 #13
0
ファイル: model.py プロジェクト: Sean858/ForumApp
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
コード例 #14
0
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()
コード例 #15
0
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})"
コード例 #16
0
ファイル: model.py プロジェクト: seongminp/ForumApp
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
コード例 #17
0
ファイル: models.py プロジェクト: 2011-01065/flask-finals
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}')"
コード例 #18
0
ファイル: model.py プロジェクト: Sean858/ForumApp
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`')
コード例 #19
0
ファイル: model.py プロジェクト: LliriKnat/Forum
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__()
コード例 #20
0
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()
コード例 #21
0
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
        }
コード例 #22
0
 def user_id(cls):
     """Foreign key to User table"""
     return db.Column(db.Integer, db.ForeignKey('users.id'))
コード例 #23
0
 def subreddit_id(cls):
     """Foreign key to Subreddit table"""
     return db.Column(db.Integer, db.ForeignKey('subreddits.id'))
コード例 #24
0
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]
        }
コード例 #25
0
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
コード例 #26
0
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)