def play(id, page=None): movie = Movie.query.get_or_404(id) if page is None: page = 1 comments = Comment.query.filter_by(movie_id=id).order_by( Comment.addtime.desc()).paginate( page, per_page=current_app.config['HOME_COMMENT_PAGE']) app = current_app._get_current_object() thread = Thread(target=async_add_playnum, args=[id, app]) thread.start() form = CommentAddForm(request.form) if request.method == 'POST' and form.validate(): if not current_user.is_authenticated: return redirect(url_for('home.login')) value = form.data value['user_id'] = current_user.id comment = Comment() comment.set_attr(value) with db.auto_commit(): db.session.add(comment) flash('添加评论成功~', 'ok') thread = Thread(target=async_add_commentnum, args=[form.movie_id.data, app]) thread.start() return redirect(url_for('home.play', id=form.movie_id.data, page=page)) return render_template('home/play.html', movie=movie, form=form, comments=comments)
def post_comment(token_data): '''comment投稿 Args: text: コメントテキスト thread_id: スレッドID Returns: 200: 正常終了 list(dict): comment情報のリスト 500: サーバエラー ''' try: params = request.json user_id = token_data.get('user_id') user = User.get(user_id=user_id) params.update({'user_id': user_id, 'name': user.get('nick_name')}) # comment作成 Comment.post(params) # comment追加後,thread_idに紐づく thread = Thread.get(thread_id=params.get('thread_id')) result = thread.get('comments') return make_response(jsonify(result), 201) except Exception as e: if str(e) == 'over text length': result = {'error_message': 'テキストが長すぎます'} return make_response(jsonify(result), 400) return make_response('', 500)
def video(id=None, page=None): """ 弹幕播放尝试 """ movie = Movie.query.get_or_404(int(id)) movie.playnum = movie.playnum + 1 form = CommentForm() if page is None: page = 1 if "user" in session and form.validate_on_submit(): data = form.data form = dict(content=data["content"], movie_id=int(id), user_id=session['user_id']) comment = Comment(form) comment.save() movie.commentnum = movie.commentnum + 1 movie.save() flash("添加评论成功!", 'ok') return redirect(url_for('index.video', id=movie.id, page=1)) movie.save() page_data = Comment.query.join(Movie).join(User).filter( id == Comment.movie_id, User.id == Comment.user_id, ).order_by(Comment.addtime.desc()).paginate(page=page, per_page=10) return render_template('home/video.html', movie=movie, form=form, page_data=page_data)
def comments(id): post = Post.query.get(int(id)) comments = ( Comment.query.filter_by(post_id=id, depth=0).order_by(Comment.created_at).all() ) form = CommentForm() if form.validate_on_submit(): if current_user.is_authenticated: c = Comment(messages=form.messages.data) c.post_id = post.id c.user_id = current_user.id c.created_at = datetime.utcnow() db.session.add(c) db.session.commit() return redirect(url_for("comment.comments", id=post.id)) return redirect(url_for("auth.login")) if request.method == "GET": form.messages.data = "" return render_template( "/comment/comment.html", title="comment", form=form, post=post, comments=comments, )
def comment_submit(id, cid = None): form = CommentForm(request.form) user = db.session.query(User).get(session['user']) image = db.session.query(Image).filter_by(id=id).one() if request.method == 'POST' and form.validate(): comment = Comment(session['user'], image, form.text.data, cid) if user.already_commented(image, cid): flash(local.comment['ALREADY_COMMENTED'], 'error') else: db.session.add(comment) db.session.flush() comment.vote(1, session['user']) db.session.commit() flash(local.comment['POSTED'], 'success') # Return user to image or comment controllers depending on ref if cid is None: return redirect(url_for('image', id=image.id)) else: return redirect(url_for('comment', id=image.id, cid=cid)) flash_errors(form) comments = construct_comment_tree(image.comments) if cid is None: try: commented = Comment.query.filter_by(id_user=session['user'], image=image, id_father=None).one() except: commented = False return render('image.html', title=image.name, commented=commented, image=image, form=form, comments=comments) else: return render('comment.html', title=local.comment['TITLE_ONE'], id=id, cid=cid, comments=comments, form=form)
def post(id): post = Post.query.get_or_404(id) form = CommentForm() if form.validate_on_submit(): if form.replied_id.data: comment = Comment(body=form.body.data, replied_id=form.replied_id.data, author=current_user._get_current_object()) page = request.args.get('page', 1, type=int) else: comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) page = 1 db.session.add(comment) db.session.commit() flash('成功发表评论') return redirect(url_for('.post', id=post.id, page=page)) page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count() - 1) // current_app.config['CMS_COMMENTS_PER_PAGE'] + 1 pagination = post.comments.filter(Comment.disabled != True).order_by( Comment.create_time.desc()).paginate( page, per_page=current_app.config['CMS_COMMENTS_PER_PAGE'], error_out=False) comments = pagination.items return render_template('blog/post.html', post=post, form=form, comments=comments, pagination=pagination)
def comment(user, post): comment = Comment() comment.body = "Is sajjan ko kya takleef hain bhai?" user.comments().save(comment) post.comments().save(comment) return comment
def execute(self, *args, **kwargs): new_comment = Comment(comment=kwargs["comment"], user=kwargs["owner"]) COMMENTS.append(new_comment) new_comment.comment_id = len(COMMENTS) new_comment.owner.comments.append( len(COMMENTS)) # store the id of the comment self._message = "Comment created successfully" return True
def test_user_has_comment_to_a_comment(self): Comment(content="This is a test comment", user_id=2, text_id=1).save() pcomment = Comment.query.first() Comment(content='This is a child comment', user_id=1, comment_id=pcomment.id).save() user = User.query.get(1) self.assertEqual(user.comments.count(), 1)
def test_user_can_downvote_a_comment(self): c1 = Comment(content="This is a test comment", user_id=2, text_id=1) c1.save() user = User.query.get(1) CommentDownvote(user_id=1, comment_id=c1.id).save() self.assertEqual(user.has_downvoted_comment.count(), 1) self.assertEqual(c1.downvoters.count(), 1)
def test_user_has_1_karma_after_commenting(self): c1 = Comment( content="This is a test comment", user_id=2, text_id=1 ) c1.save() self.assertEqual(User.query.get(2).comment_karma, 1)
def fake_comments(nums=500): with db.auto_commit(): for i in range(nums): # 已审核文章评论 data = Comment( author=faker.name(), email=faker.email(), site=faker.url(), body=faker.sentence(), timestamp=faker.date_time_this_year(), reviewed=True, post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data) for i in range(int(nums *0.1)): # 未审核评论 data = Comment( author=faker.name(), email=faker.email(), site=faker.url(), body=faker.sentence(), timestamp=faker.date_time_this_year(), reviewed=False, post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data) # 管理员评论 data = Comment( author='张小萌', email='*****@*****.**', site='example.com', body=faker.sentence(), timestamp=faker.date_time_this_year(), from_admin=True, reviewed=True, post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data) # 先 commit 评论之后才能生成针对评论的回复 with db.auto_commit(): for i in range(int(nums*0.05)): data = Comment( author=faker.name(), email=faker.email(), site=faker.url(), body=faker.sentence(), timestamp=faker.date_time_this_year(), reviewed=True, replied=Comment.query.get( random.randint(1, Comment.query.count())), post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data)
def addThirdComment(): form = request.json comment_id = form['comment_id'] comment_id = int(comment_id) #文章的id article_id = form['article_id'] #评论用户的id user_id = form['user_id'] #对谁评论的id to_user = form['to_user'] to_user = int(to_user) content = form['content'] with db.auto_commit(): comment = Comment() comment.article_id = article_id comment.article_type = 1 comment.from_uid = user_id comment.to_uid = to_user comment.origin_uid = to_user comment.content = content comment.comment_id = comment_id db.session.add(comment) article = Article.query.filter_by(id=article_id).first() article.comments += 1 return jsonify({'code': 0, 'message': '二级评论成功'})
def test_user_can_upvote_a_comment(self): c1 = Comment(content="This is a test comment", user_id=2, text_id=1) c1.save() user = User.query.get(1) CommentUpvote(user_id=1, comment_id=c1.id).save() self.assertEqual(user.has_upvoted_comment.count(), 1) # we have to count the original commenter self.assertEqual(c1.upvoters.count(), 2)
def post(self): args = post_parser.parse_args() from app.models.post import Post post = Post.query.get_or_404(args.post_id) from app.models.user import User author = User.query.get_or_404(args.author_id) comment = Comment(body=args.body, post=post, author=author) from app import db db.session.add(comment) db.session.commit() return jsonify(comment.to_json())
def add(): form = request.form u = current_user() if u is None: flash('需要进行登陆', 'info') return redirect(url_for('index.login')) comment = Comment(form) comment.user_id = u.id db.session.add(comment) db.session.commit() flash('评论成功', 'success') return redirect(url_for('post.detail', id=comment.post_id))
def comment(self, post): '''Add the comment to the post ''' content = self.request.get('content') if content: comment = Comment(post=post, user=self.user, content=content) comment.put() self.redirect('/post/%s' % str(post.key().id())) else: error = 'Please write something' self.render('view_post.html', post=post, error=error)
def test_user_has_karma_after_being_upvoted_comment(self): c = Comment( content="This is a test comment", user_id=1, link_id=1 ) c.save() for i in range(10): CommentUpvote(comment_id=c.id, user_id=i*10).save() self.assertEqual(User.query.get(1).comment_karma, 11)
def create_short_comment(): form = NewBookShortComment().validate_for_api() member_id = get_current_member().id data = { 'member_id': member_id, 'type': ClassicType.BOOK.value, 'content_id': form.book_id.data, 'short_comment': form.content.data } Comment.new_model(data, err_msg='短评不能重复提交') res_msg = form.content.data + ' +1' return Success(msg=res_msg)
def post(self, post_id=None, post=None): comment_body = self.request.get('new-comment') if comment_body: comment = Comment(parent=post.key, user=self.user.key, content=comment_body) comment.put() self.redirect_to(BlogConst.ROUTE_VIEW_POST, post_id=post_id) else: new_comment = { 'error': "Please type in a comment before submitting." } self.render_post(post, new_comment)
def create_comment(): """ 创建评论 """ for m in range(6, 10): for u in range(1, 8): form = dict( content='this is user' + str(u) + '\'s comment', movie_id=m, user_id=u + 13, ) comment = Comment(form) comment.save()
def add_comment_service(data): """ 添加评价 :param data: { # "user_name": self.user_name, # "user_id": self.user_id, "content": self.content, "product_id": self.product_id, "pic": self.pic, "real_star": self.real_star, "price_star": self.price_star, "clean_star": self.clean_star, } :return: """ session = g.session result = session.query(User).filter(User.id == data["user_id"]).one() data["user_name"] = result.username data["average_star"] = (data["real_star"] + data["price_star"] + data["clean_star"])/3 comment = Comment() for key, value in data.items(): setattr(comment, key, value) session.add(comment) session.commit() return True
def create_comment(*, account: Account, id: int, content: str) -> list: user_account_check(account) c = Comment( user=get_user_account(account), post=get_post(id), content=content, published_date=int(time.time()), ) c.save() create_notification(type='comment', account=account, post_job_id=c.post.id, receiver=c.post.user.account, comment_id=c.id) return list_comment(id=id)
def put(self, board_id, post_id, comment_id): try: form = CommentEditSchema().load(json.loads(request.data)) find_comment = Comment.objects(post_id=post_id, id=comment_id).first() if not find_comment.is_writer: return jsonify(message="본인이 작성한 댓글이 아니면 수정 할 수 없습니다."), 403 find_comment.update_comment_modified_time() comment = Comment(**form) find_comment.update(comment) except ValidationError as err: return err return jsonify(message='댓글이 수정되었습니다.'), 200
def comments(id): post = Post.query.get(int(id)) comments = Comment.query.filter_by(post_id=id, is_spam=False, depth=0).all() form = CommentForm() if form.validate_on_submit(): if current_user.is_authenticated: c = Comment(messages=form.messages.data) c.post_id = post.id c.user_id = current_user.id db.session.add(c) db.session.commit() return redirect(url_for('comment.comments', id=post.id)) return redirect(url_for('auth.login')) if request.method == 'GET': form.messages.data = '' return render_template('/comment/comment.html', title='comment', form=form, post=post, comments=comments)
def test_user_has_comment(self): Text(title='Test text', text='This is a content', user_id=1, subreddit_id=1).save() Comment(content="This is a test comment", user_id=1, text_id=1).save() user = User.query.get(1) self.assertEqual(user.comments.count(), 1)
def delete(self, board_id, post_id, comment_id): try: find_comment = Comment.objects(post_id=post_id, id=comment_id).first() find_comment.soft_delete() except ValidationError as err: return err return jsonify(message='댓글이 삭제되었습니다.'), 200
def addComment(): form = request.json article_id = form.get('article_id') user_id = form.get('user_id') content = form.get('content') article = Article.query.filter_by(id=article_id).first() user = User.query.filter_by(id=user_id).first() if article and user: with db.auto_commit(): article.comments += 1 comment = Comment() comment.article_id = article_id comment.content = content comment.from_uid = user_id db.session.add(comment) return jsonify({'code': 0, 'message': '评论成功'}) return jsonify({'code': 1, 'message': '评论失败'})
def new_post_comment(id): post = Post.query.get_or_404(id) comment = Comment.from_json(request.json) comment.author = g.current_user comment.post = post db.session.add(comment) db.session.commit() return jsonify(comment.to_json()), 201, \ {'Location': url_for('api.get_comment', id=comment.id)}
def my_written_comments(self): try: find_comments = Comment.objects(writer=g.member_id, deleted=False).order_by() #my_comments = MyCommentsSchema().dump(find_comments, many=True) except ValidationError as err: return err return jsonify(result), 200
def test_user_has_n_karma_after_commenting_n_times(self): for _ in range(10): Comment( content="This is a test comment", user_id=1, comment_id=2 ).save() self.assertEqual(User.query.get(1).comment_karma, 10)
def setUp(self): self.setup_app() self.create_user() self.create_issue() self.comment = Comment( body='foo bar', issue=self.test_issue, author=self.test_user ) self.comment.save()
def test_pre_delete(self): c = Comment(body='foo', author=self.test_user) c.issue = self.issue c.save() self.test_user.references.append(self.issue) self.test_user.save() self.issue.mentions.append(self.test_user) self.issue.comments.append(c) self.issue.save() self.assertEqual(Issue.objects.count(), 1) self.assertEqual(Comment.objects.count(), 1) self.assertEqual(len(self.test_user.references), 1) self.issue.delete() self.assertEqual(Issue.objects.count(), 0) self.assertEqual(Comment.objects.count(), 0) self.assertEqual(len(self.test_user.references), 0)
class CommentTest(AppCase): def setUp(self): self.setup_app() self.create_user() self.create_issue() self.comment = Comment( body='foo bar', issue=self.test_issue, author=self.test_user ) self.comment.save() def tearDown(self): self.teardown_dbs() def test_pre_delete(self): self.test_user.references.append(self.comment) self.test_user.save() self.test_issue.comments.append(self.comment) self.test_issue.save() self.comment.mentions.append(self.test_user) self.comment.save() self.assertEqual(Comment.objects.count(), 1) self.assertEqual(len(self.test_user.references), 1) self.assertEqual(len(self.test_issue.comments), 1) self.comment.delete() self.assertEqual(Comment.objects.count(), 0) self.assertEqual(len(self.test_user.references), 0) self.assertEqual(len(self.test_issue.comments), 0)
def convert_comment(db, site, root_url, filename): logger.info('convert %s' % filename) d = {} content = '' with open(filename) as f: for line in f: match = regex.match(line) if match: d[match.group(1)] = match.group(2) else: break is_header = True for line in f: if is_header: if line.strip(): is_header = False else: continue content = content + line # create DB record comment = Comment(site=site, author_name=d['author'], content=content) if 'email' in d: comment.author_email = d['email'].strip() if 'site' in d: comment.author_site = d['site'].strip() if 'url' in d: url = remove_from_string(d['url'], 'https://') url = remove_from_string(url, 'http://') comment.url = remove_from_string(url, root_url) # comment.url = remove_from_string(url, '/') # else: # comment.url = d['article'] if 'date' in d: pub = datetime.datetime.strptime(d['date'], '%Y-%m-%d %H:%M:%S') comment.created = pub comment.published = pub comment.save()
def teardown_dbs(self): Issue.drop_collection() User.drop_collection() Project.drop_collection() Attachment.drop_collection() Comment.drop_collection()