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 add_comment(request): """ Add a comment :param request: HttpResponse :return: JsonResponse """ status, msg = False, "Invalid Request" if request.user.is_authenticated: comment = json.loads(request.body)['comment'] type_of_post = json.loads(request.body)['type_of_post'].upper() post_id = json.loads(request.body)['post_id'] # check type_of_post is valid check = False if type_of_post == "IM": i = Image_DB.objects.filter(image_id=post_id).first() if i: check = True elif type_of_post == "CM": c = Comment_DB.objects.filter(comment_id=post_id).first() if c: check = True if check: c = Comment_DB( username=request.user.username, type_of_post=type_of_post, post_id=post_id, content=comment) c.save() status, msg = True, "Success" return JsonResponse({"status":status, "msg":msg})
def update(self, instance: Comment, validated_data: dict) -> Comment: """ :param instance: An instance of Comment that we want to update fields values. :param validated_data: Dict type :return: An instance of Comment Model. """ instance.name = validated_data.get('name', instance.name) instance.text = validated_data.get('text', instance.text) instance.save() return instance
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 get_users_comments(takes): comment_hash = [] user_hash = [] for take in takes: chapter_comments = Comment.get_comments(chapter_id=take.chunk.chapter.id) chunk_comments = Comment.get_comments(chunk_id=take.chunk.id) take_comments = Comment.get_comments(take_id=take.id) comments = list(chain(chapter_comments, chunk_comments, take_comments)) for comment in comments: user = comment.owner if user: user_hash.append( {ZipIt.get_local_file_hash(user.name_audio): FileUtility.file_name(user.name_audio)}) comment_hash.append( {ZipIt.get_local_file_hash(comment.location): FileUtility.file_name(comment.location)}) return comment_hash + user_hash
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_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 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 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 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 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 post(self): data = parser_like.parse_args() if data['value'] > 1 or data['value'] < -1: return {'error': 'value must be in range from 1 to -1'} user_id = get_jwt_identity() LikeToComment.delete_like(user_id=user_id, comment_id=data['comment_id']) new_like = LikeToComment(value=data['value'], user_id=user_id, comment_id=data['comment_id']) try: new_like.save_to_db() Comment.put_like(comment_id=data['comment_id'], value=data['value']) return { 'message': 'You liked comment with {}'.format(data['comment_id']) } except Exception as e: return {'message': 'Something went wrong'}, 500
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 get_queryset(self): queryset = [] query = self.request.query_params if len(query) == 0: return Comment.objects.all() else: pk = query.get("id", None) chapter_id = query.get("chapter_id", None) chunk_id = query.get("chunk_id", None) take_id = query.get("take_id", None) if pk is not None: queryset = Comment.objects.filter(id=pk) if chapter_id is not None: queryset = Comment.get_comments(chapter_id=chapter_id) if chunk_id is not None: queryset = Comment.get_comments(chunk_id=chunk_id) if take_id is not None: queryset = Comment.get_comments(take_id=take_id) if len(queryset) != 0: return queryset else: return None
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)
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 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 handle_comments(): comments = Comment.get_all_comments() all_comments = list(map(lambda comment: comment.serialize(), comments)) return jsonify(all_comments), 200 # @api.route('/followers', methods=['GET']) # def handle_followers(): # followers = Follower.get_all_followers() # all_followers = list(map(lambda follower: follower.serialize(), followers)) # return jsonify(all_followers), 200
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 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 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
from api.models import User, Report, ImageReport, Comment from api.serializers import UserSerializer, ReportSerializer, ImageReportSerializer, CommentSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser user = User(name='Horacio', email='*****@*****.**', password='******', profile_picture='api/media/profile_pic.png') user.save() #get id report = Report(user_fk=user, 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 content = JSONRenderer().render(userSerializer.data)
def mutate_and_get_payload(cls, root, info, comment_data): comment = Comment(**comment_data) comment.save() return IntroduceComment(comment=comment)
def post(request): """ Request: { "page": "http://foo.bar.com/blog/page/1", "content": "Hello, 来自三体世界的评论", "parent" : 0, } """ comment = Comment() comment.user_id = request.user.id comment.comment_date = timezone.now() comment.comment_page = _parse_url(request.POST.get('page'))['url'] comment.comment_content = request.POST.get('content') if request.POST.get('parent', None): try: comment.comment_parent = int(request.POST.get('parent')) except: comment.comment_type = Comment.TYPE_NORMAL else: comment.comment_type = Comment.TYPE_REPLY if comment.comment_parent > 0: try: parent = Comment.objects.get(comment_id=parent) except Comment.DoesNotExist: from . import response return response.error(400, _('Bad data'), request.POST.get('callback')) try: comment.clean_fields() except ValidationError as e: from . import response return response.error(400, _('Bad data'), request.POST.get('callback'), inner_data = e.message_dict if settings.DEBUG else None) comment.save() return JsonpResponse(data = DATA_OK, callback = request.POST.get('callback'), **KWARGS_JSON)
def create(self, validated_data): comment = Comment(**validated_data) comment.author = self.context['request'].user comment.save() return comment
def create(self, validated_data): comment = Comment(**validated_data) comment.save() return comment
}] 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 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): # {'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