def create_comment(request): if request.method == 'GET': email = request.GET.get('email', None) movie_id = request.GET.get('movie_id', None) content = request.GET.get('content', None) if email is None or movie_id is None or content is None: return JsonResponse({'status': status.HTTP_400_BAD_REQUEST}) timestamp = datetime.datetime.now().replace(tzinfo=pytz.utc) try: rating = Rating.objects.get(user__email=email, movie__id=movie_id) Comment(rating=rating, content=content, timestamp=timestamp).save() except Rating.DoesNotExist: # DoesNotExist 에러가 발행하면 return JsonResponse({ 'status': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '아직 해당 영화에 별점을 매기지 않았습니다.' }) return JsonResponse({'status': status.HTTP_200_OK}) return JsonResponse({ 'status': status.HTTP_400_BAD_REQUEST, 'msg': 'Invalid Request Method' })
def post(self): # Fetch the request json_data = request.get_json(force=True) if not json_data: return {'message': 'No input data provided'}, 400 # Validate and deserialize input data, errors = comment_schema.load(json_data) if errors: return {"status": "error", "data": errors}, 422 category_id = Category.query.filter_by(id=data['category_id']).first() if not category_id: return { 'status': 'error', 'message': 'comment category not found' }, 400 # Create the object that will be added comment = Comment(category_id=data['category_id'], comment=data['comment']) # Insert the data db.session.add(comment) db.session.commit() result = comment_schema.dump(comment).data return {'status': "success", 'data': result}, 201 result = comment_schema.dump(comment).data return {'status': "success", 'data': result}, 201
def create_article(art_dict, max_comments): """ Create article and comments from article json """ args = { k: v for k, v in art_dict.items() if k in ["title", "body", "text", "slug", "user", "tweet_id", "url"] } args["created_at"] = parse_date(art_dict) args["metadata"] = art_dict["description"] art = Article(**args) art.save() new_comments = [] elligible_comments = get_elligible_comments(art_dict["comments"]) sampled_comments = random.sample( elligible_comments, min(max_comments, len(elligible_comments))) for comm in sampled_comments: args = { k: v for k, v in comm.items() if k in ["text", "user_id", "tweet_id"] } args["created_at"] = parse_date(comm) args["text"] = preprocess_tweet(comm["text"]) comm = Comment(**args) comm.article = art new_comments.append(comm) Comment.objects.bulk_create(new_comments)
def create(self, submission_uuid, info): comment_uuid = uuid.uuid1() Comment(uuid=comment_uuid, submission_uuid=submission_uuid, author=self.user_id, info=json.dumps(info), created_timestamp=self.timestamp_now).save() return True, comment_uuid
def getting_all_comments_succeeds(self, client, init_db): post_id = Post(**self.post_data).save().id comment_data = {'body': 'test_comment', 'post_id': post_id} # save three comments for i in range(3): Comment(**comment_data).save() res = client.get('/api/comments') assert res.status_code == 200 payload = json.loads(res.data) assert len(payload['data']) == 3
def create_comment(id): data = request.get_json() or {} if 'author' not in data or 'content' not in data: return make_response(400, 'must include author and content fields') data['post_id'] = id comment = Comment() comment.from_dict(data) db.session.add(comment) db.session.commit() response = jsonify(comment.to_dict()) response.status_code = 201 return response
def post(): order_data = request.json result = OrderDao().load(order_data) if result.errors: return result.errors, 400 order = Order.create(customer_name=result.data['customer_name'], customer_email=result.data['customer_email']) comment_list = [] for comment in result.data['comments']: comment_list.append(Comment(text=comment, order_id=order.id)) Comment.bulk_create(comment_list) return order_data, 200
def comments(): if request.method == 'POST': comment = str(request.form.get('comment')) if comment == 'None': abort(400) tone = watson_tone(comment) comment = Comment(comment=comment, tone=tone) comment.save() response = jsonify(comment.serialize()) response.status_code = 201 else: comments = Comment.query.all() results = [comment.serialize() for comment in comments] response = jsonify(results) response.status_code = 200 return response
def post(self, request, *args, **kwargs): content = request.POST.get('content') aid = kwargs.get('aid') cid = request.POST.get('cid') tid = request.POST.get('tid') reply = unicode(request.POST.get('reply', '-1')) if reply == '1': comments = Comment.objects.filter(id=cid) if not comments.exists(): self.message = '回复评论不存在' self.status_code = INFO_NO_EXIST return self.render_to_response(dict()) toer = Guest.objects.get(id=tid) comment = CommentReply(comment=comments[0], to=toer) else: article = Article.objects.filter(id=aid) if not article.exists(): self.message = '评论文章不存在' self.status_code = INFO_NO_EXIST return self.render_to_response(dict()) comment = Comment() comment.belong = article[0] if content: comment.content = content else: self.message = '请输入评论内容' self.status_code = ERROR_DATA return self.render_to_response(dict()) if not self.wrap_check_token_result(): state = self.generate_state() comment.state = state comment.save() url = get_github_auth(state) return self.render_to_response({'url': url}) else: comment.author = self.user comment.review = True comment.save() send_mail('新评论', '你有一条新评论, 登陆查看 www.rapospectre.com ', '*****@*****.**', ['*****@*****.**'], fail_silently=True) if isinstance(comment, CommentReply): send_html_mail('评论回复', comment.to, comment.comment.belong, [comment.to.email]) return self.render_to_response(dict())
def setUp(self) -> None: self.users = User.objects.bulk_create( [User(**user_data) for user_data in TestData.TEST_USERS_DATA]) for user in self.users: KinGamesUser.objects.create(django_user=user) self.game = Game.objects.create(slug=self.TEST_GAME_SLUG, price=333) self.top_level_comments = Comment.objects.bulk_create([ Comment(game=self.game, user=self.users[user_index], body=body) for body, user_index in zip(self.COMMENTS_BODIES, range(3)) ]) Comment.objects.create(game=self.game, user=self.users[0], body='Reply', top_level_comment=self.top_level_comments[-1])
def comments(request): try: user = request.session['user'] order = request.data.get('order_id', '') content_star = request.data.get('content_star', '') content = request.data.get('content', '') with atomic(): comment = Comment() comment.user_id = user comment.order_id = order comment.content = content comment.content_star = content_star comment.save() data = {'code': 200, 'mes': '评价成功'} except: data = {'code': 300, 'mes': '评价失败,请稍后再试'} return JsonResponse(data)
def post(self, user): current_app.logger.debug(repr(user)) parsed_args = self.post_parser.parse_args() comment = Comment(text=parsed_args['text'], location_uuid=parsed_args['location_id'], user_uuid=user.uuid) location = HammockLocation.query.filter_by( uuid=parsed_args['location_id']).first() location.comments.append(comment) db.session.add(comment) db.session.add(location) db.session.commit() return comment
def create_comment(self, request, format=None, *args, **kwargs): user = request.user article = request.data['article_id'] article = Article.objects.get(article_id=article) recipient = None if request.data['recipient']: recipient = request.data['recipient'] recipient = MyUser.objects.get(id=recipient) if user: comment = Comment(article_id=article, title=request.data['title'], text=request.data['text'], user=user, recipient=recipient) comment.save() return (Response('Comment added'))
def post(self, request, spot_id): content = request.data['content'] score = request.data['score'] if content is None: raise ParseError('내용을 입력해주세요.') if score is None: raise ParseError('별점을 입력해주세요.') comment = Comment(spot_id=spot_id, writer=request.user, content=content, score=score) comment.save() return Response(status=200, data={'data': CommentSerializer(comment).data})
def post(self, request, room_number, question_id): request.session.save() json = JSONParser().parse(request) question = get_or_none(Question, pk=question_id) if question and question.room.number == room_number: comment = Comment(question=question, message=json['message']) comment.save() Group('room-%s' % question.room.number).send({ 'text': dumps({ 'type': 'question', 'action': 'update', 'data': QuestionSerializer(question).data }) }) return Response({}, status=204) else: return Response({'error': 'no matching question found'}, status=404)
def comment_strangething(self, request, pk=None): if 'text' in request.data: user = request.user strangething = Strangething.objects.get(id=pk) text = request.data['text'] try: comment = Comment(user=user, strangething=strangething, text=text) comment.save() response = {'message': 'Commentaire posté !'} except: comment = Comment.objects.get(user=user, strangething=strangething, text=text) response = { 'message': 'Vous avez déjà posté un commentaire identique' } return Response(response, status=status.HTTP_200_OK) else: response = {'message': 'Votre commentaire est vide..!'} return Response(response, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, post_id, format=None): username_data = get_username_from_jwt(request) if username_data['username'] != False: data = JSONParser().parse(request) serializer = CommentSerializer(data=data) if serializer.is_valid(): try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: return JsonResponse({'msg': 'Post was not found'}, status=404) comment = Comment(text=serializer.data['text'], post=post, username=username_data['username']) comment.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) return JsonResponse({'msg': username_data['error_msg']}, status=400)
}] comments = [{ "comment": "Such a goood idea" }, { "comment": "So funny cant stop laughing" }, { "comment": "Lol" }] for user in users: user_obj = User(**user) db_session.add(user_obj) db_session.commit() for post in posts: post.update( {'user_id': random.choice([user.id for user in User.query.all()])}) post_obj = Post(**post) db_session.add(post_obj) db_session.commit() for comment in comments: print("Before updatte", comment) comment.update( {'post_id': random.choice([post.id for post in Post.query.all()])}) comment.update( {'created_by': random.choice([user.id for user in User.query.all()])}) print("After updatte", comment) comment_obj = Comment(**comment) db_session.add(comment_obj) db_session.commit()
def blog_comments(request): token = request.POST.get('token') blog_id = request.POST.get('id') comments = request.POST.get('comments') comments_id = request.POST.get('comments_id') if token != '': try: obj_token = Token.objects.get(token=token) try: data = {} _id = int(blog_id) blog = Blog.objects.get(pk=_id) # create comment comment_blog = Comment(blog=blog, user=obj_token.user, comments=comments, status=1) if comments_id != None: try: comment_reply_obj = Comment.objects.get(pk=comments_id) comment_blog.comments_reply = comment_reply_obj comment_blog.save() except Comment.DoesNotExist: response = { 'result': 0, 'message': 'Error comments id' } return JsonResponse(response) else: comment_blog.save() if obj_token.user != blog.author: # create notification notifi = Notification(blog=blog, user=obj_token.user, comment=comment_blog) notifi.save() # create notification count try: notifi_count = NotificationCount.objects.get( user=blog.author) notifi_count.count += 1 notifi_count.save() except NotificationCount.DoesNotExist: notifi_count = NotificationCount(user=blog.author, count=1) notifi_count.save() data = { 'id': notifi.id, 'user_id': notifi.user.id, 'username': notifi.user.username, 'firstName': notifi.user.first_name, 'lastName': notifi.user.last_name, 'blog_id': notifi.blog.id, 'blog_title': notifi.blog.title, 'blog_author': get_token_user(notifi.blog.author.username), 'comments_name': notifi.comment.comments, 'status': notifi.status, 'comments_id': notifi.comment.id, 'created_by_image': get_profile_image(notifi.user.username) } response = {'result': 1, 'data': data, 'message': 'success'} except Blog.DoesNotExist: response = {'result': 0, 'message': 'Error id'} except Exception as e: response = {'result': 0, 'message': 'Error token'} else: response = {'result': 0, 'message': '403'} return JsonResponse(response)
def mutate_and_get_payload(cls, root, info, comment_data): comment = Comment(**comment_data) comment.save() return IntroduceComment(comment=comment)
def create(self, validated_data): comment = Comment(**validated_data) comment.save() return comment
def test_getting_single_comment_succeeds(self, client, init_db): post_id = Post(**self.post_data).save().id comment_data = {'body': 'test_comment', 'post_id': post_id} comment_id = Comment(**comment_data).save().id res = client.get(f'/api/comments/{comment_id}') assert res.status_code == 200
def create(self, validated_data): comment = Comment(**validated_data) comment.author = self.context['request'].user comment.save() return comment
def create(self, validated_data): # {'name': 'new category 4'} # name='new category 4' comment = Comment(**validated_data) comment.save() return comment
name_subject='Antonio Campos', status='encontrado', gender='masculino', birth_date='1993-02-02', state='Nayarit', city='San Blas', missing_date='2014-04-02', description='Le encanta la polla al mojo de ajo') report.save() imageReport = ImageReport(report_fk=report, image='api/media/default/missing_pic.png') imageReport.save() comment = Comment(report_fk=report, comment_date='2014-04-02', content='Me encontre un calcetin mojado') comment.save() userSerializer = UserSerializer(user) userSerializer.data rs = ReportSerializer(report) rs.data irs = ImageReportSerializer(imageReport) irs.data cs = CommentSerializer(comment) cs.data