Beispiel #1
0
def comment_create():
    if request.method == 'POST':
        c_form = CommentForm(request.args)
        if c_form.validate():
            comment = Comment(
                post=Post.query.filter_by(id=request.args['id_post']).first(),
                comment_content=request.args['comment_content'],
                id_post=request.args['id_post'])
            db.session.add(comment)
            db.session.commit()
            all_comments_post = Comment.query.filter_by(
                id_post=request.args['id_post']).all()
            return render_template('create_comment.txt',
                                   comment=comment,
                                   all_comments_post=all_comments_post)
        else:
            return jsonify(c_form.errors)
Beispiel #2
0
async def api_comment_blog(id, request, *, content):
    # check_admin(request)
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first.')
    blog = await Blog.find(id)
    if blog is None:
        raise APIResourceNotFoundError('blog is not found.')
    if not content or not content.strip():
        raise APIValueError('content', 'content cannot be empty.')
    comment = Comment(blog_id=blog.id,
                      user_id=user.id,
                      user_name=user.name,
                      user_image=user.image,
                      content=content.strip())
    await comment.save()
    return comment
Beispiel #3
0
def api_create_comment(id):
    ##通过Cookie查询登录用户
    user = cookie2user()
    if user is None:
        raise APIPermissionError('Please signin first.')
    content = request.json['content']
    if not content or not content.strip():
        raise APIValueError('content')
    blog = Blog.get(id=id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    comment = Comment(blog_id=blog.id,
                      user_id=user.id,
                      user_name=user.name,
                      user_image=user.image,
                      content=content.strip())
    return comment.to_dict()
Beispiel #4
0
def show_posts():
    posts = Blog().get_posts()
    result = []
    if not posts:
        abort(400)    
    for post in posts:
        temp = {}
        temp['id'] = post["_id"]
        temp['title'] = post["title"]
        temp['body'] = post["body"]
        comments = Comment().get_comment(post["_id"])
        if comments is not None:
            tree = arrangecomments(comments)
            temp['comments'] = tree 
        result.append(temp)
    # result = [{col: getattr(d, col) for col in cols} for d in post]
    return jsonify({"Post":result})
Beispiel #5
0
def home(id):
    from models import Post, Comment
    from forms import PostForm, CommentForm
    if request.method == 'POST':
        print(request.form)
        form = CommentForm(request.form)

        if form.validate():
            comment = Comment(**form.data)
            db.session.add(comment)
            db.session.commit()

            flash('Comment created!')

    post = Post.query.filter_by(id=id).first()
    comments = Comment.query.filter_by(post_id=id)
    return render_template('article.html', post=post, comments=comments)
Beispiel #6
0
async def manage_reply(request, reply_to_id, content):
    if request.__user__:
        if request.__user__.admin:
            reply_to_comment = await Comment.Find(reply_to_id)
            comment = Comment(
                blog_id=reply_to_comment.blog_id,
                user_id=request.__user__.id,
                user_name=request.__user__.name,
                reply_to=reply_to_comment.user_name,
                parent_id=reply_to_id if reply_to_comment.parent_id == '0' else
                reply_to_comment.parent_id,
                content=content,
                blog_name=reply_to_comment.blog_name)
            await comment.insert()
            return web.json_response()
    logging.warning('Try reply without permission')
    return web.HTTPForbidden()
Beispiel #7
0
async def commentTest(loop):
    await orm.create_pool(loop,
                          host='192.168.125.116',
                          user='******',
                          password='******',
                          db='awesome')
    b = Comment(user_id='0015290387322034e831203fda641f9a44caeea44d4902a000',
                user_name='Test03',
                blog_id='blog1',
                content='content1!!!',
                user_image='about:blank')
    await b.save()
    comments = await Comment.findAll()
    for c in comments:
        print(c)
        c['content'] = 'change content test!'
        await c.update()
def addComment(passage_id, comment_incline, comment_content):

    comment = Comment(passage_id, comment_incline, comment_content)
    db_session.add(comment)

    query = db_session.query(Passage)
    targetPassage = query.filter(Passage.passage_id == passage_id).one()

    targetPassage.commentNumber = targetPassage.commentNumber + 1
    if comment_incline == UP:
        targetPassage.up = targetPassage.up + 1
    if comment_incline == MUTUAL:
        targetPassage.mutual = targetPassage.mutual + 1
    if comment_incline == DOWN:
        targetPassage.down = targetPassage.down + 1

    db_session.commit()
Beispiel #9
0
def comment_add(chatter_id):
    """
    Add comment to post
    """

    if not g.user:
        flash("You need to be logged in to do this", "danger")
        return redirect("/")

    form = CommentForm()
    if form.validate_on_submit():
        new_comment = Comment(body=form.body.data, user_id=g.user.id)
        chatter = Chatter.query.get(chatter_id)
        chatter.comments.append(new_comment)
        db.session.commit()

        return redirect(f"/chatters/{chatter_id}")
Beispiel #10
0
def newpost():
    pid = request.args.get('pid')
    form = PostForm(pid=pid)
    if request.method == 'GET':
        return render_template('newpost.html', form=form)
    else:
        if not Problem.query.filter_by(
                pid=form.pid.data).all() or not form.validate_title():
            return 'error'

        comment = Comment(pid = form.pid.data, userid = current_user.userid, \
                            nickname = current_user.nickname, title = form.title.data, \
                            content = form.content.data, post_time = get_now_time())

        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('discuss', pid=form.pid.data))
Beispiel #11
0
    def post(self):
        # 取出参数
        content = self.get_argument('content')
        wb_id = int(self.get_argument('wb_id'))
        user_id = int(self.get_cookie('user_id'))

        # 插入评论内容
        session = Session()
        comment = Comment(user_id=user_id,
                          wb_id=wb_id,
                          content=content,
                          created=datetime.datetime.now())  # 创建 comment 对象
        session.add(comment)  # 插入单条数据
        session.commit()

        # 跳回原来的页面
        self.redirect('/weibo/show?weibo_id=%s' % wb_id)
async def api_create_comment(*, blog_id, request, content):
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first')
    if not content or not content.strip():
        raise APIValueError('content', 'content cannot be empty')

    blog = await Blog.find(blog_id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    comment = Comment(blog_id=blog.id,
                      user_id=user.id,
                      user_name=user.name,
                      user_image=user.image,
                      content=content.strip())
    await comment.save()
    return comment
Beispiel #13
0
def posts_create_comment(username: str, id: str):
    schema = Schema({
        "content": And(str, len, error="No content specified")
    })
    validated = schema.validate(request.json)

    try:
        post = Post.objects(pk=id).first()
    except ValidationError:
        return jsonify({"error": "Post not found"}), 404

    user = User.objects(username=username).first()
    comments = post.comments
    comments.append(Comment(user=user, content=validated["content"]))
    post.save()

    return jsonify([comment.to_public_json() for comment in post.comments][::-1])
Beispiel #14
0
    def post(self, comment_id):
        '''Add a comment reply to this comment.'''
        args, author_name = parse_and_decode()

        text = bleach.clean(args['text'], strip=True)

        parent = get_comment(comment_id)
        author_id = get_author_add_if_needed(author_name)

        now = arrow.utcnow()
        comment = Comment(author_id=author_id, text=text,
                          thread_id=parent.thread_id,
                          created=now, modified=now,
                          parent_id=parent.id)
        db.session.add(comment)
        db.session.commit()
        return get_thread_comments(comment.thread)
Beispiel #15
0
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {"message": "No input data provided"}
        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"}
        comment = Comment(category_id=data['category_id'],
                          comment=data['comment'])
        db.session.add(comment)
        db.session.commit()

        result = comment_schema.dump(comment).data
        return {'status': 'success', 'data': result}, 201
Beispiel #16
0
async def api_create_comment(id, request, *, content):
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first.')
    if not content or not content.strip():
        raise APIValueError('content should not be empty.')
    # 查找此评论的对应的博客是否存在
    blog = await Blog.find(id)
    if blog is None:
        raise APIResourceNotFoundError('Blog Not Found')
    comment = Comment(blog_id=blog.id,
                      user_id=user.id,
                      user_name=user.name,
                      user_image=user.image,
                      content=content.strip())
    await comment.save()
    return comment
Beispiel #17
0
async def create_blog_comment(id, request, *, content):
    user = request.__user__
    if not user:
        raise APIPermissionError('permission sigin first')
    if not content or not content.strip():
        raise APIValueError('comment', 'comment is empty')
    blog = await Blog.find(id)
    if not blog:
        raise APIResourceNotFoundError('not exist blog id')
    comment = Comment(blog_id=blog.id,
                      user_id=user.id,
                      user_name=user.name,
                      user_image=user.image,
                      content=content.strip())
    logging.info('handler comment: %s' % str(comment))
    await comment.save()
    return comment
Beispiel #18
0
def api_create_blog_comment(blog_id):
    user = ctx.request.user
    if user is None:
        raise APIPermissionError('Need signin.')
    blog = Blog.get(blog_id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    content = ctx.request.input(content='').content.strip()
    if not content:
        raise APIValueError('content')
    c = Comment(blog_id=blog_id,
                user_id=user.id,
                user_name=user.name,
                user_image=user.image,
                content=content)
    c.insert()
    return dict(comment=c)
Beispiel #19
0
    def post(self, post_id, uid, post):
        comment = self.request.get("comment")

        # Save comment and user Post.comment and redirect to MainPage
        # In case of no comment rerender the page with errormessage
        if comment:
            c = Comment(content=comment,
                        authorid=User.get_by_id(int(uid)).key,
                        postid=post.key)
            c.put()
            post.comments = [c.key] + post.comments
            post.put()
            time.sleep(0.2)
            self.redirect("/")
        else:
            error = "Enter comment please!"
            self.render("comment.html", comment=comment, error=error)
Beispiel #20
0
def addComment():
    user_id = str(uuid.uuid1())
    email = request.form.get('email')
    comment_content = request.form.get('comment')
    article_id = request.form.get('article_id')
    if Check.inDictElement(comment_content):
        return u'Your comments should not include dirty words.'

    user = User(id=user_id, email=Check.hiddenEmail(email))
    comment = Comment(content=comment_content )
    comment.author = user
    article = Article.query.filter(Article.id == article_id).first()
    comment.article = article

    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('detail',article_id=article_id))
Beispiel #21
0
def contacto():
    comment_form = forms.CommentForm(request.form)

    if request.method == 'POST' and comment_form.validate():

        # Validar user id
        user_id = session['user_id']

        comment = comment_form.comment.data
        comment = Comment(user_id=user_id, text=comment)
        db.session.add(comment)
        db.session.commit()
        success_message = 'Comentario ingresado correctamente'
        flash(success_message)

    titulo = 'Comentarios'
    return render_template('formulario.html', title=titulo, form=comment_form)
Beispiel #22
0
def api_create_blog_comment(blog_id):
    '''
    创建评论
    '''
    blog = Blog.get(blog_id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    content = ctx.request.input(content='').content.strip()
    if not content:
        raise APIValueError('content')
    c = Comment(blog_id=blog_id,
                user_id=1,
                user_name='匿名',
                user_image='',
                content=content)
    c.insert()
    return dict(comment=c)
Beispiel #23
0
def comment_add(request):

    if request.method == 'POST':

        group_id = request.POST.get('group', '')

        detail = request.POST.get('detail', '')

        if group_id and detail:
            comment = Comment()
            comment.article = Group(id=group_id)
            comment.detail = detail
            comment.save()

        return HttpResponseRedirect('/myGroupDetail_member/%s' % group_id)

    return render_to_response('myGroupDetail_member.html',)
Beispiel #24
0
def new_comm(post_id):
    if request.method == 'POST':
        user = User.query.filter_by(username=current_user.username).first()
        post = Post.query.filter_by(id=post_id).first()
        text = escape(request.form['text'])
        comment = Comment(user=user, post=post, text=text)
        db.session.add(comment)
        db.session.commit()

        comments = Comment.query.filter_by(post_id=post_id).all()
        comments_json = {}
        for comm in comments:
            comments_json[comm.id] = {
                "content": escape(comm.text),
                "date": str(comm.date)
            }
        return jsonify(comments_json)
Beispiel #25
0
def api_create_comment(request, *, blog_id, content):
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first.')
    if not content or not content.strip():
        raise APIValueError('content')
    blog = yield from Blog.find(blog_id)
    print("blog--------->" + blog.id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    if blog is not None and blog.commentState == '0':
        raise APIValueError('prohibiting', '该文章已禁止评论.')
    comment = Comment(blog_id=blog_id,
                      user_id=user.id,
                      content=content.strip())
    yield from comment.save()
    return comment
def recipe(id):
    recipe = Recipe.query.get_or_404(id)
    enableComments = False
    commForm = AddCommentForm()

    if 'email' in session:
        enableComments = True
        if request.method == 'POST':
            if commForm.validate():
                newComment = Comment(commForm.commentdesc.data,
                                     session['email'])
                recipe.comments.append(newComment)
                db.session.commit()
    return render_template("recipe.html",
                           recipe=recipe,
                           enableComments=enableComments,
                           form=commForm)
Beispiel #27
0
def api_create_comment(id, request, *, content):
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first.')
    if not content or not content.strip():
        raise APIValueError('content')
    blog = yield from Blog.find(id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    comment = Comment(
        blog_id=blog.id,
        user_id=user.id,
        user_name=user.name,
        user_image=user.image,
        content=content.strip())
    yield from comment.save()
    return comment
Beispiel #28
0
def create_comment(session, authorId, postId, content, properties):
    print("Creating a comment")
    try:
        comment = Comment()
        comment.authorId = authorId
        comment.postId = postId
        comment.postedAt = datetime.now().isoformat()
        comment.content = content
        session.add(comment)
        session.commit()
        session.refresh(comment)  # Needs this to refer to comment.id
        return json.dumps(
            {
                'comment_id': comment.id,
                'http_response': 200,
                'created_at': comment.postedAt
            },
            indent=2,
            default=str)
    except (sqlalchemy.exc.InterfaceError, sqlalchemy.exc.OperationalError):
        print(
            "Database is down, crashing service. Restarting, sending default error on rapid"
        )
        jsonObject = json.dumps(
            {
                'comment_id': 9999999,
                'http_response': 403,
                'created_at': 9999999
            },
            indent=2,
            default=str)
        properties.headers['http_response'] = 503
        send("ConfirmCommentCreation", jsonObject, properties)
        exit()
        #raise Exception("Database is down, crashing service. Restarting, sending default error on rapid")
    except Exception as e:
        print("[-] Exception ", e.__class__, " occurred.")
        return json.dumps(
            {
                'comment_id': 9999999,
                'http_response': 403,
                'created_at': 9999999
            },
            indent=2,
            default=str)
Beispiel #29
0
def receive_comment(sid, data):
    our_guy = clients[str(sid)]

    comment = Comment(data['commentId'], data['postId'], data['authorId'],
                      data['text'], data['mentions'])
    if comment.postId == "-1":
        print("Discussion - bad id.")
        sio.emit('comment_reply', 'Error. Bad id.')

    response = Discussion.query.filter_by(postId=comment.postId).all()
    if (not response) or (comment.mentions == ['-1']
                          and comment.authorId == our_guy):
        print("Discussion: no discussion. Creating new one.")
        print([
            comment.commentId, comment.mentions, comment.text, comment.authorId
        ])
        new_disc = Base(comment.postId, [[
            comment.commentId, comment.mentions, comment.text, comment.authorId
        ]])
        users_disc = [u for u in new_disc.comments]
        db_disc = Discussion(comment.postId + comment.commentId,
                             comment.postId, comment.commentId,
                             comment.authorId, users_disc,
                             jsonpickle.encode(new_disc.comments),
                             len(new_disc.comments), False, False)

        db.session.add(db_disc)
        db.session.commit()
    else:
        for discussion in response:
            comments = [
                [k] + v
                for (k, v) in jsonpickle.decode(discussion.discussion).items()
            ]
            new_disc = Base(discussion.rootId, comments)
            new_disc.addnew(comment.mentions, comment.text, comment.commentId,
                            comment.authorId)
            users_disc = [u for u in new_disc.comments]
            discussion.users = users_disc
            discussion.discussion = jsonpickle.encode(new_disc.comments)
            discussion.length = len(new_disc.comments)
        db.session.commit()

    export_to_ml()
    send_veil()
Beispiel #30
0
def add_comment(request):
    if request.method == 'POST':
        subject = request.POST['subject']
        content = request.POST['content']
        paper_id = request.POST['paper_id']
        paper = Paper.objects.get(id=paper_id)
        try:
            username = get_user_fromcookie(request)
            print username
        except:
            print sys.exc_info()
        obj = Comment(user_id=username,
                      subject=subject,
                      content=content,
                      paper_id=paper)
        obj.save()
        return HttpResponse(json.dumps({'status': '200'}))
    return HttpResponse(json.dumps({'status': 501}))