def add_comment_to_post(request, post_id): """POST interface to add a comment to a post. Expect the following items in the JSON body: username claim argument parent_comment_id (optional) is_agreement """ data = json.loads(request.body) required_data = [ "username", "claim", "argument", "is_agreement", ] for key in required_data: if key not in data: return HttpResponse("Missing data to create comment.", status=401) search_results = Post.objects.filter(id=post_id) if search_results: target_post = search_results.first() else: return HttpResponse("No post found with given post id.") search_results = User.objects.filter(username=data["username"]) if search_results: target_user = search_results.first() else: return HttpResponse("No user found with given username.") new_comment = Comment(user=target_user, claim=data["claim"], argument=data["argument"], is_agreement=data["is_agreement"], parent_post=target_post) if "parent_comment_id" in data: search_results = Comment.objects.filter(id=data["parent_comment_id"]) if search_results: target_comment = search_results.first() else: return HttpResponse( "No comment found with given parent_comment_id.") new_comment.parent_comment = target_comment new_comment.save() return HttpResponse("New comment saved to post. ID=" + str(new_comment.id))
def create_comment(user_id, post_id, text): # Create a comment and add it to the post user_obj = User.query.filter(User.id == user_id).first() post_obj = Post.query.filter(Post.id == post_id).first() community = post_obj.community # Raises AttributeError if post_obj is None # Permission checks if user_obj is None: raise ValueError("user doesn't exist") if user_obj in community.banned_users: # User is banned from the community and is therefore not allowed to comment raise PermissionError("user {} is banned in community {}".format(user_obj, community)) # Locked post check if post_obj.is_locked: # FIXME: owners, admins, and mods should still be able to comment on locked posts raise PermissionError("post {} is locked".format(post_obj)) # Privacy setting checks - in practice, the user shouldn't even be able to see # the thread at all if the community is set to private. # But, until we implement the verification in a different layer of the request processing, # we will verify it here, for now. if community.is_private and user_obj not in community.users: raise PermissionError("community {} is private".format(community)) # Checks passed, let's create the post. comment = Comment(user_id=user_id, post_id=post_id, text=text) db.session.add(comment) try: db.session.commit() except exc.IntegrityError: # some field in the comment object is None db.session.rollback() raise
def add_data(self): logging.basicConfig(level=logging.INFO) logging.info('testing add data...') try: for i in range(0, 10): user = User(id=i + 1, student_id=f"{i+1}", username=f"ct{i+1}", password=encrypt_helper("123"), email=f"bz{i}@163.com", phone=f"123{i}") db.session.add(user) db.session.flush() except Exception as e: logging.error(f'error when adding users: {e}') try: for i in range(0, 10): task = Task(id=i + 1, title='cbbmjm哈哈', creator_id=f"{i%2+1}", task_type=f"{i%3+1}", reward=100, description="pptmjj", due_time="2019-07-02 18:00", max_participate=i % 3 + 1) db.session.add(task) db.session.flush() except Exception as e: logging.error(f'error when adding tasks: {e}') try: for i in range(0, 10): comment = Comment(user_id=i + 1, task_id=i + 1, content="Nice!") db.session.add(comment) db.session.flush() except Exception as e: logging.error(f'error when adding comments: {e}') try: for i in range(0, 10): collect = Collect(user_id=i + 1, task_id=i + 1) db.session.add(collect) db.session.flush() except Exception as e: logging.error(f'error when adding collects: {e}') try: for i in range(0, 10): participate = Participate(user_id=i + 1, task_id=i % 2 + 1, status=1) db.session.add(participate) db.session.flush() except Exception as e: logging.error(f'error when adding participates: {e}') db.session.commit() logging.info('testing add data succeed')
def send_comment(request): post_data = request.body.decode('utf-8') post_data = json.loads(post_data) url = post_data.get('url') open_id = post_data.get('open_id') nick_name = post_data.get('nickname') avatar = post_data.get('avatar') comment = post_data.get('value') comment_id = open_id + str(int(time.time())) cur = datetime.datetime.now() new_comment = Comment(url=url,open_id=open_id,nickname=nick_name,avatar=avatar,value=comment,comment_id=comment_id,like_count=0,cur=cur,verify=0) new_comment.save() return HttpResponse(content='ok')
def post_comment(article_id): data = request.form.to_dict() comment_content = data['body'] user = current_user comment = Comment(body=comment_content, user_id=user.id, article_id=article_id) db.session.add(comment) db.session.commit() resp = make_response(jsonify(data), 201) # HTTP协议要求201响应包含一个值为新资源URL的Location头部 resp.headers['Location'] = 'comment/' + str(comment.id) return resp
def new(): data = request.get_json() print('data --------->', data) newComment = Comment(user_id=data["user_id"], grid_id=data["grid_id"], content=data["content"]) db.session.add(newComment) db.session.commit() return jsonify(message='added comment to db'), 200
def get(self): user_id = request.args.get('user_id') task_id = request.args.get('task_id') comments = Comment.get(user_id=user_id, task_id=task_id) result = [{"id": comment.id, "user_id": comment.user_id, "task_id": comment.task_id, "content": comment.content, "likes": comment.likes} for comment in comments] for value in result: user_id = value['user_id'] user = User.get(user_id=user_id)[0] value['username'] = user.username return dict(data=result), 200
def delete(self): form = request.get_json(True, True) user_id = auth_helper() comment_id = form.get('comment_id') if not comment_id: return dict(error="请指定评论"), 400 comment = Comment.get(comment_id=comment_id) if not comment: return dict(error="评论不存在"), 400 comment = comment[0] if user_id != comment.user_id: return dict(error="只能删除自己的评论"), 400 db.session.delete(comment) db.session.commit() return dict(data="删除评论成功"), 200
def patch(self): # 修改comment内容 form = request.get_json(True, True) user_id = auth_helper() comment_id = form.get('comment_id') content = form.get('content') if not comment_id: return dict(error="请指定评论"), 400 comment = Comment.get(comment_id=comment_id) if not comment: return dict(error="评论不存在"), 400 comment = comment[0] if user_id != comment.user_id: return dict(error="只能修改自己的评论"), 400 comment.content = content db.session.commit() return dict(data='修改评论成功'), 200
def update_likes(): # 修改评论点亮数(点亮/点灭) form = request.get_json(True, True) comment_id = form.get('comment_id') like = form.get('like') if not comment_id: return jsonify(error='请指定评论'), 400 if not like or (like != 'yes' and like != 'no'): return jsonify(error='请提供正确的看法(点亮 or 点灭?)'), 400 comment = Comment.get(comment_id=comment_id) if not comment: return jsonify(error='评论不存在'), 400 comment = comment[0] if like == 'yes': comment.likes += 1 else: comment.likes -= 1 db.session().commit() return jsonify(data='操作成功'), 200
def post(self): user_id = auth_helper() form = request.get_json(True, True) task_id = form.get('task_id') if not task_id: return dict(error='请指定任务'), 400 content = form.get('content') if not content: return dict(error='评论内容不能为空'), 400 try: comment = Comment(user_id=user_id, task_id=task_id, content=content) db.session.add(comment) db.session.commit() except exc.IntegrityError as e: logging.error(f'create comment failed, msg: {e}') if re.search(r"Cannot add or update a child row", e.orig.args[1]): return dict(error='任务不存在'), 400 else: return dict(error=f'{e}'), 400 return dict(data="评论成功"), 200
def test_delete_comment(self): user = create_test_user() community = create_test_community() post = create_test_post(user, community) # Manually create the comment comment = Comment(user_id=user.id, post_id=post.id, text="F*****g comment lol shit") db.session.add(comment) db.session.commit() cid = comment.id # Now verify first that it exists, and then delete it and verify that it doesn't comment = Comment.query.filter(Comment.id == cid).first() self.assertIsNotNone(comment) # Delete comment_functions.delete_comment(cid) # verify it's None comment = Comment.query.filter(Comment.id == cid).first() self.assertIsNone(comment) # Cleanup cleanup(Post, Community, User)
def get(self): find_collect = request.args.get('find_collect') user_id = request.args.get('user_id') tasks = [] if find_collect and find_collect is True and user_id: collects = Collect.get(user_id=user_id) for collect in collects: task = Task.get(task_id=collect.task_id) if task: tasks.append(task[0]) else: creator_id = request.args.get("creator_id") title = request.args.get('title') task_type = request.args.get("task_type") min_reward = request.args.get("min_reward") max_reward = request.args.get("max_reward") offset = request.args.get("offset") limit = request.args.get("limit") tasks = Task.get(creator_id=creator_id, title=title, task_type=task_type, min_reward=min_reward, max_reward=max_reward, offset=offset, limit=limit) if len(tasks) != 1: # 按发布时间逆序 for i in range(0, len(tasks) - 1): for j in range(i + 1, len(tasks)): if tasks[i].id < tasks[j].id: t = tasks[i] tasks[i] = tasks[j] tasks[j] = t result = [{ "task_id": task.id, "title": task.title, "task_type": task.task_type, "reward": task.reward, "description": task.description, "due_time": task.due_time.strftime("%Y-%m-%d %H:%M"), "max_participate": task.max_participate, "creator_id": task.creator_id, "image": task.image.decode() if task.image else None } for task in tasks] for value in result: creator = User.get(value["creator_id"])[0] value["creator_name"] = creator.username participators = [{ "user_id": p.user_id, "status": ParticipateStatusCN[p.status] } for p in Participate.get(task_id=value["task_id"])] for p in participators: user = User.get(user_id=p["user_id"])[0] p["username"] = user.username p["phone"] = user.phone p["email"] = user.email p["avatar"] = user.avatar.decode() if user.avatar else None value["participators"] = participators user_id = auth_helper() collect = Collect.get(user_id=user_id, task_id=value['task_id']) value['is_collect'] = True if collect else False # 是否收藏该任务 comments = Comment.get(task_id=value['task_id']) value['num_comments'] = len(comments) if comments else 0 # 任务的评论数 return dict(data=result, count=len(result)), 200