Ejemplo n.º 1
0
    def post(self):
        body = request.get_json()
        fields = ['picture_id', 'message']
        if not fields_are_in(body, fields):
            return {'error': 'Missing a field'}, 400
        if is_empy_or_none(body):
            return {'error': 'A field is empty or None'}, 400

        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()

        if current_user is None:
            return {
                'error': 'Header token is not good, please login again'
            }, 401

        picture = Picture.objects(id=body.get('picture_id')).first()

        if picture is None:
            return {'error': 'Picture id does not exist in database'}, 401
        comment = {
            'user': current_user.username,
            'message': body.get('message')
        }

        comment = Comment(**comment)
        comment.save()

        Picture.objects(id=body.get('picture_id')).update_one(
            push__comments=comment)
        Picture.objects(id=body.get('picture_id')).update_one(
            nb_comments=picture.nb_comments + 1)

        return {'message': 'Comment successfully added to picture'}, 200
Ejemplo n.º 2
0
 def post(self, request, postID):
     if request.user.is_authenticated:
         name = request.user.username
         body = request.POST.get("body")
         post = Post.objects.get(id=postID)
         comment = Comment(postedBy=name, body=body)
         comment.post = post
         comment.save()
         return HttpResponseRedirect("/post/%s" % postID)
     return HttpResponseRedirect("/accounts/login")
Ejemplo n.º 3
0
    def create_dummy_comment(self, **kwargs):
        card = kwargs.get('card', self.create_dummy_card())
        content = kwargs.get('content', self.get_random_string(20))
        user = kwargs.get('created_by', self.create_dummy_user())

        instance = Comment(card=card, created_by=user, content=content)
        instance.save()
        card.comments.append(instance)
        card.save()
        return instance
Ejemplo n.º 4
0
def addcomment(req):
    # print(req.user.)
    if not req.user.is_authenticated:
        return Http404()
    data = req.body.decode('utf8')
    data = json.loads(data)
    post = data.get('post')
    content = data.get('content')
    comment = Comment(by = req.user, post = Post.objects.get(id=post), content = content)
    comment.save()
    return JsonResponse({'status' : True})
Ejemplo n.º 5
0
def comment(request, pk):
	form = CommentSection(request.POST)
	body = form['body'].value()
	user = request.user
	commodity = get_object_or_404(Commodity, id=request.POST.get('stuff_id'))
	comment = Comment(
		commodity=commodity,
		user=user,
		body=body,
	)
	comment.save()
	return redirect('web:home')
Ejemplo n.º 6
0
def add_comments(request, cid):
    authorized = check_authorized(Capsule, cid, request.user.username, 'add')
    if isinstance(authorized, JsonResponse):
        return authorized
    fields = json.loads(request.body)
    fields['owner'] = request.user
    fields['capsule'] = Capsule.objects.filter(cid=cid, deleted=False).get()
    comment = Comment(**fields)
    comment.save()
    return Response({
        "status": "resource created",
        "comid": comment.comid
    },
                    status=status.HTTP_201_CREATED)
Ejemplo n.º 7
0
 def post(self):
     try:
         user_id = get_jwt_identity()
         body = request.get_json()
         user = User.objects.get(id=user_id)
         comment = Comment(**body, user=user)
         comment.save()
         id = comment.id
         return {'id': str(id)}, 200
     except (FieldDoesNotExist, ValidationError):
         raise SchemaValidationError
     except NotUniqueError:
         raise CommentAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Ejemplo n.º 8
0
def add_comment(data, user_id):
    event_id = data.get('event_id')
    text = data.get('text')
    if not text:
        raise Exception("You can't post an empty comment")
    new_comment = Comment(user_id, event_id, text)
    db.session.add(new_comment)
    db.session.commit()
    return new_comment
Ejemplo n.º 9
0
 def get(self, coach_id):
     try:
         coach = Coach.objects.get(id=coach_id)
         comments = Comment.objects(coach=coach).to_json()
         return Response(comments, mimetype="application/json", status=200)
     except DoesNotExist:
         raise CommentNotExistsError
     except Exception:
         raise InternalServerError
Ejemplo n.º 10
0
def savecomment():
    form = request.form
    print(form)
    phone = session["user"]["phone"]
    dbs = Comment(place_id=form["plcid"],
                  comment=form["comment"],
                  user_id=phone).save()
    resp = jsonify({'message': 'comment successful update'})
    resp.status_code = 200
    return resp
Ejemplo n.º 11
0
 def post(self, card_id):
     try:
         user_id = get_jwt_identity()
         body = request.get_json()
         user = User.objects.get(id=user_id)
         card = Card.objects.get(id=card_id)
         comment = Comment(**body, sender=user)
         card.comments.append(comment)
         card.save()
         return '', 200
     except (FieldDoesNotExist, ValidationError):
         raise SchemaValidationError
     except Exception:
         raise InternalServerError
Ejemplo n.º 12
0
    def post(self, post_id):
        try:
            user_id = get_jwt_identity()
            post = Post.objects.get(id=post_id)
            user = User.objects.get(id=user_id)

            body = request.get_json()
            comment = Comment(**body, post=post, author=user)
            comment.save()

            post.comments.append(comment)
            post.save()

            id = comment.id
            socketio.emit('update', {}, room='post' + str(post.id))

            return {'id': str(id)}, 200
        except InvalidQueryError:
            raise SchemaValidationError
        except DoesNotExist:
            raise DocumentMissing
        except Exception:
            raise InternalServerError
Ejemplo n.º 13
0
 def post(self):
     try:
         user_id = get_jwt_identity()
         body = request.get_json()
         user = User.objects.get(id=user_id)
         thread_id = ObjectId(body['thread'])
         thread = Thread.objects.get(id=thread_id)
         comment = Comment(**body, created_by=user)
         comment.save()
         user.update(push__comments=comment)
         user.save()
         thread.update(push__comments=comment)
         thread.save()
         id = thread.id
         return {'id': str(id)}, 200
     except (FieldDoesNotExist, ValidationError) as exc:
         print(exc)
         raise SchemaValidationError
     except NotUniqueError:
         raise AlreadyExistsError
     except Exception as e:
         print(e)
         raise InternalServerError
Ejemplo n.º 14
0
def create_comment(ticket_id):
    error = validate_ticket(ticket_id)
    if error is not None:
        return error
    body = request.get_json()
    if body is None:
        return jsonify({'message': "content can not empty"}), 400
    content = body.get('content', None)
    if content is None:
        return jsonify({'message': "content can not empty"}), 400
    user_id = get_jwt_identity()
    comment = Comment(userId=user_id, content=content, createTime=current_milli_time(), ticketId=ticket_id) \
        .save()

    return jsonify(comment), 200
Ejemplo n.º 15
0
def addComment(request):
	#发布评论比较简单,就是检查登录状况,检查对应博客是否存在
	if (not request.user.is_authenticated):
		return HttpResponse("Please log in.", status = 400)
	if (request.POST == None):
		return HttpResponse("Only POST is allowed.", status = 400)
	
	if (not request.POST.get('content')):
		return HttpResponse("Content missing.", status = 400)
	try:
		blog = Blog.objects.filter(id = int(request.POST.get('blog')))[0]
	except:
		return HttpResponse("Blog not found.", status = 400)
		
	Comment(author = request.user, blog = blog, content = request.POST.get('content')).save()
	return HttpResponse("Add successfully.", status = 200)
Ejemplo n.º 16
0
def main():
    # Remember the last post for each subreddit
    # in order to not retrieve the same posts again
    last_post = {}

    subreddits = _config.get('subreddits', [])

    while True:
        for sr in subreddits:
            subreddit = _reddit_client.get_subreddit(sr)

            # Get latests posts for this subreddit
            post_models = []
            for post in subreddit.get_new(
                    limit=_config.get('posts-limit', 1),
                    params={"before": last_post.get(sr)}
            ):
                post_models.append(Post(post))

                # Get comments associated with this post
                comment_models = []
                post.replace_more_comments(limit=16, threshold=10)
                for comment in praw.helpers.flatten_tree(post.comments):
                    comment_models.append(Comment(comment, subreddit=sr))

                # Insert comments
                try:
                    _mongo.insert_many(comment_models)
                except:
                    _log.error('Unable to insert comments', exc_info=True)

                # Remember last post to not fetch it again
                last_post[sr] = post.fullname

            # Insert post
            try:
                _mongo.insert_many(post_models)
            except:
                _log.error('Unable to insert posts', exc_info=True)

        # Request limiter
        time.sleep(_config.get('rate-limit', 1))
Ejemplo n.º 17
0
    def get(self, username):
        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()

        if current_user is None:
            return {'error': 'Header token is not good, please login again'}, 401

        user_info = User.objects(username=username).first()

        if user_info is None:
            return {'error': 'User {} does not exist'.format(username)}, 401

        user_info = json.loads(user_info.to_json())

        del user_info['password']
        del user_info['image_queue']
        del user_info['_id']
        del user_info['nb_login']
        del user_info['dates']
        del user_info['following']

        user_info['already_follow'] = False

        for user in user_info['followers']:
            if user['$oid'] == user_id:
                user_info['already_follow'] = True
                break
        del user_info['followers']

        for pic in range(len(user_info['pictures'])):
            user_info['pictures'][pic] = json.loads(Picture.objects(id=user_info['pictures'][pic]['$oid']).first().to_json())
            user_info['pictures'][pic]['id'] = user_info['pictures'][pic]['_id']['$oid']
            del user_info['pictures'][pic]['_id']
            del user_info['pictures'][pic]['date']
            del user_info['pictures'][pic]['owner']
            for com in range(len(user_info['pictures'][pic]['comments'])):
                user_info['pictures'][pic]['comments'][com] = json.loads(Comment.objects(id=user_info['pictures'][pic]['comments'][com]['$oid']).first().to_json())
                del user_info['pictures'][pic]['comments'][com]['_id']
        user_info['pictures'] = user_info['pictures'][::-1]

        return Response(json.dumps(user_info), mimetype="application/json", status=200)
Ejemplo n.º 18
0
def loadcomment():
    try:
        table = "<table><tr><td>Phone Number</td><td>Comment</td></tr>"
        tkno = request.form
        print(tkno)
        for ticket in Comment.objects(place_id=tkno["plcid"]):
            table += "<tr><td>{}</td><td>{}</td></tr>".format(
                ticket.user_id, ticket.comment)
        table += "</table>"
        print(table)
        errors = {}
        errors['message'] = 'success'
        errors['data'] = table
        resp = jsonify(errors)
        resp.status_code = 201
        return resp
    except:
        resp = jsonify({'message': 'No data found'})
        resp.status_code = 400
        return resp
Ejemplo n.º 19
0
def create_comment(db: Session, comment: NewComment,
                   user_role: Optional[str]) -> Comment:
    """
    Create new user-submitted comment.

    :param Session db: ORM database session.
    :param NewComment comment: User comment object.
    :param Optional[str] user_role: Permissions of the comment author, if any.

    :returns: Comment
    """
    try:
        LOGGER.info(
            f"Creating comment from {comment.user_email} on {comment.post_slug}..."
        )
        new_comment = Comment(
            user_id=comment.user_id,
            user_name=comment.user_name,
            user_avatar=comment.user_avatar,
            user_email=comment.user_email,
            user_role=user_role,
            body=comment.body,
            post_slug=comment.post_slug,
            post_id=comment.post_id,
            created_at=datetime.now(),
        )
        db.add(new_comment)
        db.commit()
        LOGGER.success(
            f"New comment created by user `{new_comment.user_name}` on post `{new_comment.post_slug}`"
        )
        return new_comment
    except SQLAlchemyError as e:
        LOGGER.error(f"SQLAlchemyError while creating comment: {e}")
    except IntegrityError as e:
        LOGGER.error(f"IntegrityError while creating comment: {e}")
    except Exception as e:
        LOGGER.error(f"Unexpected error while creating comment: {e}")
Ejemplo n.º 20
0
    def get(self):
        # Get current requesting user
        user_id = get_jwt_identity()
        current_user = User.objects(id=user_id).first()
        if current_user is None:
            return {'error': 'Header token is not good, please login again'}, 401

        pictures = current_user.image_queue
        if len(pictures) == 0:
            return Response(json.dumps(pictures), mimetype="application/json", status=200)

        pictures = [json.loads(i.to_json()) for i in pictures]
        pictures = pictures[::-1]
        for i in range(len(pictures)):
            pic_id = pictures[i]['_id']['$oid']
            del pictures[i]['_id']
            del pictures[i]['date']
            pictures[i]['id'] = pic_id
            for j in range(len(pictures[i]['comments'])):
                pictures[i]['comments'][j] = json.loads(Comment.objects(id=pictures[i]['comments'][j]['$oid']).first().to_json())
                del pictures[i]['comments'][j]['_id']

        return Response(json.dumps(pictures), mimetype="application/json", status=200)
Ejemplo n.º 21
0
                            )
                        )
posts = getSerializers(dname = "posts", 
    dmodel = Post,
    dfields = ('id', 'by', 'content','title', 'created_at', 'modified_at'), 
    pred = lambda x: Post(
                            by = User.objects.get(id = x['by']),
                            content = x['content'] 
                            )
                        )
comments = getSerializers(dname = "comments", 
    dmodel = Comment,
    dfields = ('id','post', 'by', 'content', 'created_at', 'modified_at'), 
    pred = lambda x: Comment(
                            by = User.objects.get(id = x['by']),
                            post = Post.objects.get(id = x['post']), 
                            content = x['content'] 
                            )
                        )
router =  [replies, comments, posts]


def loggedIn(req):
    # print(req.user.)
    if req.user.is_authenticated:
        return JsonResponse({ 'auth' : True , 'token' : get_token(req), 'user' : str(req.user)})
    return JsonResponse({ 'auth' : False, 'token' : get_token(req), 'user' : str(req.user)})

import json

Ejemplo n.º 22
0
 def get(self):
     comments = Comment.objects().to_json()
     return Response(comments, mimetype="application/json", status=200)
Ejemplo n.º 23
0
def submit_comment(token_type,user_info):
    result={'code':1,'msg':'ok'}
    try:
        data=request.get_json()
        order_no=data['order_no']
        order_details=OrderDetail.query.filter_by(order_no=order_no)
        
        for order_detail in order_details:
            comment=Comment()
            comment.goods_id=order_detail.goods_id
            comment.shop_id=data['shop_id']
            comment.buyer_id=user_info.buyer_id
            comment.level=data['level']
            comment.content=data['content']
            comment.del_flag='0'
            comment.order_no=order_no
            comment.comment_type='1'
            comment.commit_time=datetime.now()
            comment.is_read='0'
            db.session.add(comment)
            db.session.commit()
    except Exception,e:
        current_app.logger.exception(e)
        result['code']=0
        result['msg']='ok'