def comment_id(value): """ 检查是否是评论id :param value: 被检验的值 :return: comment_id """ try: _comment_id = int(value) except Exception: raise ValueError('Invalid target comment id.') else: if _comment_id <= 0: raise ValueError('Invalid target comment id.') else: ret = cache_comment.CommentCache(_comment_id).exists() if ret: return _comment_id else: raise ValueError('Invalid target comment id.')
def post(self): """ 创建评论 """ json_parser = RequestParser() json_parser.add_argument('target', type=positive, required=True, location='json') json_parser.add_argument('content', required=True, location='json') json_parser.add_argument('art_id', type=parser.article_id, required=False, location='json') args = json_parser.parse_args() target = args.target content = args.content article_id = args.art_id if not content: return {'message': 'Empty content.'}, 400 allow_comment = cache_article.ArticleInfoCache( article_id or target).determine_allow_comment() if not allow_comment: return {'message': 'Article denied comment.'}, 400 if not article_id: # 对文章评论 article_id = target comment_id = current_app.id_worker.get_id() comment = Comment(id=comment_id, user_id=g.user_id, article_id=article_id, parent_id=None, content=content) db.session.add(comment) db.session.commit() # TODO 增加评论审核后 在评论审核中添加缓存 cache_statistic.ArticleCommentCountStorage.incr(article_id) try: cache_comment.CommentCache(comment_id).save(comment) except SQLAlchemyError as e: current_app.logger.error(e) cache_comment.ArticleCommentsCache(article_id).add(comment) # 发送评论通知 _user = cache_user.UserProfileCache(g.user_id).get() _article = cache_article.ArticleInfoCache(article_id).get() _data = { 'user_id': g.user_id, 'user_name': _user['name'], 'user_photo': _user['photo'], 'art_id': article_id, 'art_title': _article['title'], 'timestamp': int(time.time()) } current_app.sio.emit('comment notify', data=_data, room=str(_article['aut_id'])) else: # 对评论的回复 exists = cache_comment.CommentCache(target).exists() if not exists: return {'message': 'Invalid target comment id.'}, 400 comment_id = current_app.id_worker.get_id() comment = Comment(id=comment_id, user_id=g.user_id, article_id=article_id, parent_id=target, content=content) db.session.add(comment) db.session.commit() # TODO 增加评论审核后 在评论审核中添加评论缓存 cache_statistic.ArticleCommentCountStorage.incr(article_id) cache_statistic.CommentReplyCountStorage.incr(target) try: cache_comment.CommentCache(comment_id).save(comment) except SQLAlchemyError as e: current_app.logger.error(e) cache_comment.CommentRepliesCache(target).add(comment) return { 'com_id': comment.id, 'target': target, 'art_id': article_id }, 201