Exemple #1
0
    def post(self, post_id):
        if not self.user:
            self.redirect('/blog/login')
            return

        # get all the data
        post_bundle = PostService.get_post_bundle(
            post_id=int(post_id),
            user=self.user)
        error_msg = ''

        # checking which button was pressed
        if self.request.POST.get('submit_comment'):
            comment = self.request.get('comment_content')
            if comment:
                new_comment = PostService.add_comment(
                    comment=self.request.get('comment_content'),
                    post_id=int(post_id),
                    user_id=self.user.key().id()
                )
                # updating the bundle with the new comment
                post_bundle.comments.insert(0, new_comment)
            else:
                error_msg = "Please enter a comment"

        elif self.request.POST.get('update_comment'):
            comment_id = self.request.POST.get('comment_id')
            comment_author = int(self.request.POST.get('comment_author'))
            if comment_author != self.user.key().id():
                error_msg = "You can edit only your own comments"
            else:
                self.redirect('/blog/editcomment/' + str(comment_id))

        elif self.request.POST.get('edit_post'):
            if post_bundle[0].created_by != self.user.key().id():
                error_msg = "You can edit only your own posts"
            else:
                self.redirect('/blog/editpost/' + str(post_id))

        elif self.request.POST.get('like'):
            new_like, error_msg = PostService.like_update(
                post_id=int(post_id),
                user_id=self.user.key().id()
            )
            # updating the bundle with the new like
            post_bundle = post_bundle._replace(like=new_like)

        elif self.request.POST.get('delete_comment'):
            comment_id = self.request.POST.get('comment_id')
            updated_comments, error_msg = PostService.delete_comment(
                post_id=int(post_id),
                comment_id=int(comment_id),
                user_id=self.user.key().id()

            )
            # updating the bundle updated list of comments
            post_bundle = post_bundle._replace(comments=updated_comments)

        elif self.request.POST.get('delete_post'):
            posts, error_msg = PostService.delete_post(
                post_id=int(post_id),
                user_id=self.user.key().id()
            )
            if not error_msg:
                time.sleep(0.5)
                self.redirect('/blog')
                return

        self.render('showpost.html',
                    error=error_msg,
                    **post_bundle._asdict())  # passing the bundle as dictionary