def _generate_comments( _count: int, reviewed: bool = True, from_admin: bool = False, is_replied: bool = False ): """ 生成评论数据,内部调用 :param _count: 生成的评论数量 :param reviewed: default=True,默认是已审核评论 :param from_admin: default=False,默认不是管理员评论 :param is_replied: default=False,默认不是回复评论 :return: None """ comments_count = Comment.query.count() posts_count = Post.query.count() for i in range(_count): with db.auto_commit(): comment = Comment() if not from_admin: comment.author = cls.FAKER.name() comment.email = cls.FAKER.email() comment.site = cls.FAKER.url() else: comment.author = Admin.query.get(1).nickname comment.email = "*****@*****.**" comment.site = "localhost:5000" comment.content = cls.FAKER.text(random.randint(40, 200)) comment.from_admin = from_admin comment.reviewed = reviewed if is_replied: comment.replied = Comment.query.get(random.randint(1, comments_count)) comment.post = Post.query.get(random.randint(1, posts_count)) db.session.add(comment)
def test_get_comment(self): # 测试返回单个评论 u1 = User(username='******', email='*****@*****.**') u1.set_password('123') u2 = User(username='******', email='*****@*****.**') u2.set_password('123') p = Post(title='first post from david', body='post from david', author=u2, timestamp=datetime.utcnow() + timedelta(seconds=1)) c1 = Comment(body='first comment from john') c1.author = u1 c1.post = p c2 = Comment(body='second comment from john') c2.author = u1 c2.post = p db.session.add(u1) db.session.add(u2) db.session.add(p) db.session.add(c1) db.session.add(c2) db.session.commit() headers = self.get_token_auth_headers('david', '123') response = self.client.get('/api/comments/1', headers=headers) self.assertEqual(response.status_code, 200) # 判断返回的评论集合 json_response = json.loads(response.get_data(as_text=True)) self.assertEqual(json_response['body'], 'first comment from john') self.assertEqual(json_response['author']['username'], 'john')
def test_get_post_comments(self): # 测试返回用户自己的博客列表 # 创建用户 u1 = User(username='******', email='*****@*****.**') u1.set_password('123') u2 = User(username='******', email='*****@*****.**') u2.set_password('123') u3 = User(username='******', email='*****@*****.**') u3.set_password('123') p = Post(title='first post from john', body='post from john', author=u1, timestamp=datetime.utcnow() + timedelta(seconds=1)) c1 = Comment(body='first comment from david') c1.author = u2 c1.post = p c2 = Comment(body='second comment from susan') c2.author = u3 c2.post = p db.session.add_all([u1, u2, u3, p, c1, c2]) db.session.commit() headers = self.get_token_auth_headers('john', '123') response = self.client.get('/api/posts/1/comments/', headers=headers) self.assertEqual(response.status_code, 200) json_response = json.loads(response.get_data(as_text=True)) self.assertEqual(json_response['_meta']['total_items'], 2) self.assertIsNotNone(json_response.get('items')) self.assertEqual(json_response['items'][0]['body'], 'second comment from susan') # 倒序排列 self.assertEqual(json_response['items'][1]['body'], 'first comment from david')
def test_update_comment(self): # 测试修改单个评论 u1 = User(username='******', email='*****@*****.**') u1.set_password('123') u2 = User(username='******', email='*****@*****.**') u2.set_password('123') u3 = User(username='******', email='*****@*****.**') u3.set_password('123') p = Post(title='first post from david', body='post from david', author=u2, timestamp=datetime.utcnow() + timedelta(seconds=1)) c1 = Comment(body='first comment from john') c1.author = u1 c1.post = p c2 = Comment(body='first comment from susan') c2.author = u3 c2.post = p db.session.add(u1) db.session.add(u2) db.session.add(u3) db.session.add(p) db.session.add(c1) db.session.add(c2) db.session.commit() headers = self.get_token_auth_headers('john', '123') # 1. 不允许修改别人的评论 data = json.dumps({'body': 'Hello, I am john'}) response = self.client.put('/api/comments/2', headers=headers, data=data) self.assertEqual(response.status_code, 403) # 2. 没提供任何参数时 data = json.dumps({}) response = self.client.put('/api/comments/1', headers=headers, data=data) self.assertEqual(response.status_code, 400) json_response = json.loads(response.get_data(as_text=True)) self.assertEqual(json_response['message'], 'You must post JSON data.') # 3. 缺少 body 时 # data = json.dumps({'disabled': True}) # response = self.client.put('/api/comments/1', headers=headers, data=data) # self.assertEqual(response.status_code, 400) # json_response = json.loads(response.get_data(as_text=True)) # self.assertEqual(json_response['message'], 'Body is required.') # 4. 正常提供参数,成功修改 data = json.dumps({'body': 'Hello, I am john'}) response = self.client.put('/api/comments/1', headers=headers, data=data) self.assertEqual(response.status_code, 200) # 判断返回的信息中时候已更改了body字段 json_response = json.loads(response.get_data(as_text=True)) self.assertEqual(json_response['body'], 'Hello, I am john')
def create_comment(): '''create new comment in post''' data = request.get_json() if not data: return bad_request('you must have a Json data.') if not 'body' in data or not data.get('body').strip(): return bad_request('Body is required.') if not 'post_id' in data or not data.get('post_id'): return bad_request('Post id is required.') post = Post.query.get_or_404(int(data.get('post_id'))) comment = Comment() comment.from_dict(data) comment.author = g.current_user comment.post= post db.session.add(comment) db.session.commit() # 新增评论的时候把通知写入db if data.get('parent_id'): #是回复就通知回复的对象 reply_comment = Comment.query.get_or_404(int(data.get('parent_id'))) reply_comment.author.add_notification('unread_recived_comments_count',reply_comment.author.new_recived_comments()) else: #是评论就通知文章作者,。 print('评论') post.author.add_notification('unread_recived_comments_count',post.author.new_recived_comments()) db.session.commit() response = comment.to_dict() return response
def comment_for_microkno(is_micropub, data, microknow): comment = Comment() comment.from_dict(data) comment.author = g.current_user if is_micropub: comment.micropub = microknow else: comment.microcon = microknow # 必须先添加该评论,后续给各用户发送通知时,User.new_recived_comments() 才能是更新后的值 db.session.add(comment) db.session.commit() # 更新数据库,添加评论记录 # 添加评论时: # 1. 如果是一级评论,只需要给微知识作者发送新评论通知 # 2. 如果不是一级评论,则需要给微知识作者和该评论的所有祖先的作者发送新评论通知 users = set() users.add(microknow.author) # 将微知识作者添加进集合中 if comment.parent: ancestors_authors = {c.author for c in comment.get_ancestors()} users = users | ancestors_authors # 给各用户发送新评论通知 for u in users: u.add_notification('unread_recived_comments_count', u.new_recived_comments()) db.session.commit() # 更新数据库,写入新通知 response = jsonify(comment.to_dict()) response.status_code = 201 # HTTP协议要求201响应包含一个值为新资源URL的Location头部 response.headers['Location'] = url_for('api.get_comment', id=comment.id) return response
def create_comment(): '''在某篇博客文章下面发表新评论''' data = request.get_json() if not data: return bad_request('You must post JSON data.') if 'body' not in data or not data.get('body').strip(): return bad_request('Body is required.') if 'post_id' not in data or not data.get('post_id'): return bad_request('Post id is required.') post = Post.query.get_or_404(int(data.get('post_id'))) comment = Comment() comment.from_dict(data) comment.author = g.current_user comment.post = post db.session.add(comment) # 给文章作者发送新评论通知 post.author.add_notification('unread_recived_comments_count', post.author.new_recived_comments()) db.session.commit() response = jsonify(comment.to_dict()) response.status_code = 201 # HTTP协议要求201响应包含一个值为新资源URL的Location头部 response.headers['Location'] = url_for('api.get_comment', id=comment.id) return response
def post(self, blog_id=1, page=1): data = request.json blog = Blog.query.get(blog_id) comment = Comment() comment.detail = data['detail'] user_id = data['user_id'] user = User.query.get(user_id) if user: comment.author = user else: guest = User('guest','unused') guest.id = 0 comment.author = guest comment.article = blog comment.createAt = datetime.now() db.session.add(comment) db.session.commit() comments = Comment.query.filter_by(article=blog).paginate(page, PAGE_SIZE, False) return comments
def comment_for_cradle(data, cradle): comment = Comment() comment.from_dict(data) comment.author = g.current_user comment.cradle = cradle db.session.add(comment) db.session.commit() response = jsonify(comment.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_comment', id=comment.id) return response
def add_comment(articleid): comment = request.get_json().get("comment") article_id = request.get_json().get("article_id") comment = Comment(comment=comment) user_id = session.get('user_id') user = User.query.filter_by(id=user_id).first() comment.author = user article = Article.query.filter_by(id=article_id).first() comment.article = article db.session.add(comment) db.session.commit() return jsonify({"result": "success to add comment"}), 200
def save(self, qid, commit=True): answer = Comment(text=self.cleaned_data['text']) answer.author = self.auhtor answer.question = Question.objects.get(id=qid) answer.dateTime = timezone.now() if commit: answer.save() like = LikeComment(comment=answer) dis = DisLikeComment(comment=answer) like.save() dis.save() return answer
def test_delete_comment(self): # 测试删除单个评论 u1 = User(username='******', email='*****@*****.**') u1.set_password('123') u2 = User(username='******', email='*****@*****.**') u2.set_password('123') u3 = User(username='******', email='*****@*****.**') u3.set_password('123') p = Post(title='first post from david', body='post from david', author=u2, timestamp=datetime.utcnow() + timedelta(seconds=1)) c1 = Comment(body='first comment from john') c1.author = u1 c1.post = p c2 = Comment(body='first comment from susan') c2.author = u3 c2.post = p db.session.add(u1) db.session.add(u2) db.session.add(u3) db.session.add(p) db.session.add(c1) db.session.add(c2) db.session.commit() headers = self.get_token_auth_headers('john', '123') # 1. 不允许删除别人的评论 response = self.client.delete('/api/comments/2', headers=headers) self.assertEqual(response.status_code, 403) # 2. 删除自己的评论是成功的 response = self.client.delete('/api/comments/1', headers=headers) self.assertEqual(response.status_code, 204) self.assertEqual(response.get_data(as_text=True), '')
def post(self, slug): context = self.get_context(slug) form = context.get('form') if form.validate(): comment = Comment() form.populate_obj(comment) comment.author = context.get('author') post = context.get('post') post.comments.append(comment) post.save() return redirect(url_for('posts.detail', slug=slug)) return render_template('posts/detail.html', **context)
def create_comment(): """发布一条评论""" json_data = request.json if not json_data: return bad_request('You must post JSON data.') if 'body' not in json_data or not json_data.get('body').strip(): return bad_request('Body is required.') if 'post_id' not in json_data or not json_data.get('post_id'): return bad_request('Post id is required.') post = Post.query.get_or_404(int(json_data.get('post_id'))) comment = Comment() comment.from_dict(json_data) comment.author = g.current_user comment.post = post db.session.add(comment) db.session.commit() # 获取当前评论所有的祖先评论的作者 users = set() users.add(comment.post.author) if comment.parent: ancestors_authors = {c.author for c in comment.get_ancestors()} users = users | ancestors_authors # 给所有的祖先评论作者发送通知 for u in users: u.add_notification('unread_recived_comments_count', u.new_recived_comments()) db.session.commit() response = jsonify(comment.to_dict()) response.status_code = 201 # 201响应的请求头中要包含一个location response.headers['Location'] = url_for('api.get_comment', id=comment.id) # 给用户发送新评论的通知 post.author.add_notification('unread_recived_comments_count', post.author.new_recived_comments()) return response
def staticUnity(slug): if request.method == 'POST': unity = Unity.get_or_404(slug=slug) form = CommentForm() if not form.validate(): return render_template('unity/staticUnity.html', pageTitle=unity.title, unity=unity, form=form) else: newComment = Comment(body=form.comment.data) newComment.author = User.get(email=current_user.email) unity.comments.append(newComment) unity.save() form.comment.data = None # resets field on refresh flash('Comment Posted') return render_template('unity/staticUnity.html', pageTitle=unity.title, unity=unity, form=form) elif request.method == 'GET': try: return render_template('unity/%s.html' % slug, pageTitle=slug) except TemplateNotFound: unity = Unity.get_or_404(slug=slug) currentUser = User.get(email=current_user.email) if (unity.postType == 'draft' and unity.author != currentUser and currentUser.is_admin() is False): flash('You must be draft author or admin to view.') return redirect(url_for('.listUnity')) else: form = CommentForm() return render_template('unity/staticUnity.html', pageTitle=unity.title, unity=unity, form=form)
def create_comment(): '''在某篇博客文章下面发表新评论''' data = request.get_json() if not data: return bad_request('You must post JSON data.') if 'body' not in data or not data.get('body').strip(): return bad_request('Body is required.') if 'post_id' not in data or not data.get('post_id'): return bad_request('Post id is required.') post = Post.query.get_or_404(int(data.get('post_id'))) comment = Comment() comment.from_dict(data) comment.author = g.current_user comment.post = post # 必须先添加该评论,后续给各用户发送通知时,User.new_recived_comments() 才能是更新后的值 db.session.add(comment) db.session.commit() # 更新数据库,添加评论记录 # 添加评论时: # 1. 如果是一级评论,只需要给文章作者发送新评论通知 # 2. 如果不是一级评论,则需要给文章作者和该评论的所有祖先的作者发送新评论通知 users = set() users.add(comment.post.author) # 将文章作者添加进集合中 if comment.parent: ancestors_authors = {c.author for c in comment.get_ancestors()} users = users | ancestors_authors # 给各用户发送新评论通知 for u in users: u.add_notification('unread_recived_comments_count', u.new_recived_comments()) db.session.commit() # 更新数据库,写入新通知 response = jsonify(comment.to_dict()) response.status_code = 201 # HTTP协议要求201响应包含一个值为新资源URL的Location头部 response.headers['Location'] = url_for('api.get_comment', id=comment.id) return response