当前位置: 首页>>代码示例>>Python>>正文


Python models.Comment类代码示例

本文整理汇总了Python中app.models.Comment的典型用法代码示例。如果您正苦于以下问题:Python Comment类的具体用法?Python Comment怎么用?Python Comment使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Comment类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_submissionsentiment_model

def test_submissionsentiment_model(session):
    s = Submission.create(session, **MOCK_SUBMISSION)

    c1 = Comment.create(session, **MOCK_COMMENT1)
    c1_sentiment = comment_sentiment(c1)
    c1s = CommentSentiment.create(session, **c1_sentiment)

    c2 = Comment.create(session, **MOCK_COMMENT2)
    c2_sentiment = comment_sentiment(c2)
    c2s = CommentSentiment.create(session, **c2_sentiment)

    comments = session.query(Comment).options(joinedload("sentiment")).all()

    comment_sentiments = []
    for c in comments:
        comment_sentiments.append({"polarity": c.sentiment.polarity, "subjectivity": c.sentiment.subjectivity})

    submission_sentiment = comment_sentiment_avg(comment_sentiments)
    submission_sentiment.update({"submission_id": s.id})

    ss = SubmissionSentiment.create(session, **submission_sentiment)

    submission_sentiments = session.query(SubmissionSentiment).all()
    ss1 = submission_sentiments[0]

    # test object form
    assert ss1.id == 1
    assert ss1.submission_id == s.id
    for k in submission_sentiment.keys():
        assert getattr(ss1, k) == submission_sentiment[k]

    # test values
    assert ss1.polarity < 0.5 and ss1.polarity > -0.5
    assert ss1.subjectivity > 0.8
开发者ID:PsyBorgs,项目名称:redditanalyser,代码行数:34,代码来源:test_models.py

示例2: addComment

def addComment(request):
    """
    Respond to an HTTP request to add a comment to an oligo, at the URL ...app/addComment

    :param primer: oligo primer
    :param rating: user's rating
    :type rating: 1 - 5
    :param comment: user's comment
    :return: new comment list
    """
    if request.method == 'GET':
        q = request.GET
        if q.__contains__('primer'):
            if q.__contains__('rating'):
                rating = q['rating']
            else:
                rating = 0;
            if q.__contains__('text'):
                text = html.escape(q['text']) #escape evil embedded html
            elif q.__contains__('rating') == False:
                return HttpResponseBadRequest(json.dumps({'error': 'at least one of rating or text is required'}))
            else:
                text = '';
            comment = Comment(
                primer = q['primer'],
                rating = rating,
                text = text
            )
            comment.save()
            return findComments(q['primer'])
        return HttpResponseBadRequest(json.dumps({'error': 'primer is required'}))
    return HttpResponseBadRequest(json.dumps({'error':'POST not supported'}))
开发者ID:ucscHexmap,项目名称:djangoOligo,代码行数:32,代码来源:views.py

示例3: test_commentsentiment_model

def test_commentsentiment_model(session):
    s = Submission.create(session, **MOCK_SUBMISSION)

    c1 = Comment.create(session, **MOCK_COMMENT1)
    c1_sentiment = comment_sentiment(c1)
    c1s = CommentSentiment.create(session, **c1_sentiment)

    c2 = Comment.create(session, **MOCK_COMMENT2)
    c2_sentiment = comment_sentiment(c2)
    c2s = CommentSentiment.create(session, **c2_sentiment)

    # test object form
    for k in c1_sentiment.keys():
        assert getattr(c1s, k) == c1_sentiment[k]

    # test relationship
    assert c1.sentiment == c1s

    # test values
    assert c1s.id == 1
    assert c1s.polarity > 0.5
    assert c1s.subjectivity > 0.8
    assert c2s.id == 2
    assert c2s.polarity < -0.5
    assert c2s.subjectivity > 0.8
开发者ID:PsyBorgs,项目名称:redditanalyser,代码行数:25,代码来源:test_models.py

示例4: recreate_data

def recreate_data():
    """Generate fake data for development and testing"""
    print 'dropping existing tables...'
    db.drop_all()
    print 'creating tables...'
    db.create_all()
    print 'inserting roles...'
    Role.insert_roles()
    print 'creating admin user...'
    u1 = User(username='ralph', email='[email protected]', password='r',
              name='Ralph Wen', location='Hangzhou, China',
              about_me='This is the creator of everything', confirmed=True)
    db.session.add(u1)
    print 'creating moderate user...'
    u2 = User(username='yadong', email='[email protected]', password='r',
              name='Yadong Wen', location='Hangzhou, China',
              about_me='Yeah', confirmed=True)
    db.session.add(u2)
    db.session.commit()
    print 'generating 50 normal users...'
    User.generate_fake(50)
    print 'generating 500 posts...'
    Post.generate_fake(500)
    print 'generating follows...'
    User.generate_following()
    print 'generating comments...'
    Comment.generate_comments()
    print '...done'
开发者ID:ralphite,项目名称:flask-blog,代码行数:28,代码来源:manage.py

示例5: rebuild

def rebuild():
    if config == 'development':
        with app.app_context():
            db.drop_all()
            db.create_all()
            Role.insert_roles()
            admin_me = User(email=app.config['FLASKR_ADMIN'],
                            username=app.config['MY_USERNAME'],
                            password=app.config['MY_PASSWORD'],
                            confirmed=True,
                            name=forgery_py.name.full_name(),
                            location=forgery_py.address.city(),
                            about_me=forgery_py.lorem_ipsum.sentences(10),
                            member_since=forgery_py.date.date(True,
                                                              min_delta=10))
            db.session.add(admin_me)
            ordinary_me = User(email=forgery_py.internet.email_address(),
                               username='exm',
                               password='exm',
                               confirmed=True,
                               name=forgery_py.name.full_name(),
                               location=forgery_py.address.city(),
                               about_me=forgery_py.lorem_ipsum.sentences(10),
                               member_since=forgery_py.date.date(True,
                                                                 min_delta=10))
            db.session.add(ordinary_me)
            db.session.commit()
            User.generate_fake(30)
            Post.generate_fake(500)
            Follow.generate_fake(500)
            Comment.generate_fake(500)
    else:
        print('Permission denied.')
开发者ID:SFurnace,项目名称:flaskr,代码行数:33,代码来源:manage.py

示例6: comment_new

def comment_new(id):
    post = Post.get_by_id(id)

    if post is None or post.is_hidden:
        abort(404)

    form = CommentForm()

    if form.is_submitted():
        try:
            if not form.validate():
                raise Exception(_('ERROR_INVALID_SUBMISSION'))

            comment = Comment(user=current_user, post=post)
            form.populate_obj(comment)
            comment.save()

            flash(_('COMMENT_SAVE_SUCESS'))

            if comment.parent_comment:
                send_email('reply_comment', comment)
            else:
                send_email('comment', post, comment)

            return redirect(url_for('stamp.show',
                                    id=post.id,
                                    _anchor='comment-%s' % comment.id))

        except Exception as e:
            flash(e.message, 'error')

    return render_template('main/stamp/show.html',
                           post=post,
                           form=form)
开发者ID:jctt1983,项目名称:PythonBlog,代码行数:34,代码来源:index.py

示例7: article

def article(post_id):
    login_form = LoginForm()
    register_form = RegistrationForm()
    post = Post.query.get_or_404(post_id)
    if request.method == 'POST':
        if not current_user.is_authenticated():
            return 'please log in '
        data = request.get_json(force=True)
        if 'content' in data.keys():
            if 'self_ref_id' in data.keys():
                # user cannot be set directly to current_user because this is a context variable proxy object.
                # the expression current_user._get_current_object() returns the actual User object.
                # user = current_user._get_current_object()
                comment = Comment(content=data['content'], user_id=current_user.id, post_id=post_id,
                                  self_ref_id=data['self_ref_id'])
                response_data = {'content': data['content'], 'user': current_user.nickname,
                                 'ref_user': Comment.query.get(int(data['self_ref_id'])).user.nickname}
            else:
                comment = Comment(content=data['content'], user_id=current_user.id, post_id=post_id)
                response_data = {'content': data['content'], 'user': current_user.nickname}
            comment.save()
            return json.dumps(response_data)
        if 'voted' in data.keys():
            if data['voted'] == 'False' and not post.was_voted_by(current_user):
                post.do_vote(current_user)
                voted = 'True'
            else:
                post.cancel_vote(current_user)
                voted = 'False'
            return json.dumps({'count': post.votes.count(), 'voted': voted})

    comments = Post.query.get(post_id).comments
    form = CommentOnPostForm()
    return render_template('blog/post.html', post=post, form=form, comments=comments,
                           login_form=login_form, register_form=register_form)
开发者ID:cymoo,项目名称:very-simple,代码行数:35,代码来源:blog.py

示例8: test_notification_list

 def test_notification_list(self):
     db.create_all()
     u1 = User(email='[email protected]', username='john', password='cat')
     u2 = User(email='[email protected]', username='susan', password='cat')
     t = Talk(title='t', description='d', author=u1)
     c1 = Comment(talk=t, body='c1', author_name='n1',
                  author_email='[email protected]', approved=True)
     c2 = Comment(talk=t, body='c2', author_name='n2',
                  author_email='[email protected]', approved=True, notify=False)
     c3 = Comment(talk=t, body='c3', author=u2, approved=True)
     c4 = Comment(talk=t, body='c4', author_name='n4',
                  author_email='[email protected]', approved=False)
     c5 = Comment(talk=t, body='c5', author=u2, approved=True)
     c6 = Comment(talk=t, body='c6', author_name='n6',
                  author_email='[email protected]', approved=True, notify=False)
     db.session.add_all([u1, u2, t, c1, c2, c3, c4, c5])
     db.session.commit()
     email_list = c4.notification_list()
     self.assertTrue(('[email protected]', 'n1') in email_list)
     self.assertFalse(('[email protected]', 'n2') in email_list)  # notify=False
     self.assertTrue(('[email protected]', 'susan') in email_list)
     self.assertFalse(('[email protected]', 'n4') in email_list)  # comment author
     self.assertFalse(('[email protected]', 'n6') in email_list)
     email_list = c5.notification_list()
     self.assertFalse(('[email protected]', 'john') in email_list)
     self.assertTrue(('[email protected]', 'n4') in email_list)  # comment author
开发者ID:ErinCall,项目名称:flask-pycon2014,代码行数:26,代码来源:test_comment_model.py

示例9: create

 def create(self, request, apikey, apisignature):
     print "creating"
     if not key_check( apikey, apisignature, '/idea/comment/'):
         return {'error':'authentication failed'}
     else:
         print 
         commentForm = CommentForm({"comment":request.POST['comment']})
         if commentForm.is_valid():
             print "form valid"
             clean = commentForm.cleaned_data
             print clean
             print request.POST
             idea = Idea.objects.get(id = request.POST['idea_id'])
             print idea
             try:
                 print "trying"
                 comment = Comment(
                     text = clean['comment'], 
                     user = User.objects.get(id = request.POST['user_id']), 
                     idea = idea)
                 print comment
             except Idea.DoesNotExist:
                 return {'error':'no idea'}
             except User.DoesNotExist:
                 return {'error':'no user'}
             else:
                 comment.save()
                 #helpers.filter_tags(clean['tags'], idea)
                 print comment
                 return comment
         else:
             return {'error':'no comment'}
开发者ID:simonv3,项目名称:ideas,代码行数:32,代码来源:handlers.py

示例10: comment_view

def comment_view(request, identifier):
    if request.method == 'POST':
        snippet = Snippet.objects.get(pk=(int(identifier)))
        c = Comment(
            snippet=snippet, user=request.user, text=request.POST['text'])
        c.save()
        return redirect('/snippet/' + identifier)
开发者ID:dmitry-yakutkin,项目名称:snippetshare,代码行数:7,代码来源:views.py

示例11: test_comment_sentiment_avg

def test_comment_sentiment_avg(session):
    s = Submission.create(session, **const.MOCK_SUBMISSION)

    c1 = Comment.create(session, **const.MOCK_COMMENT1)
    c1_sentiment = sentiment.comment_sentiment(c1)
    c1s = CommentSentiment.create(session, **c1_sentiment)

    c2 = Comment.create(session, **const.MOCK_COMMENT2)
    c2_sentiment = sentiment.comment_sentiment(c2)
    c2s = CommentSentiment.create(session, **c2_sentiment)

    comments = session.query(Comment).\
        options(joinedload('sentiment')).\
        all()

    comment_sentiments = []
    for c in comments:
        comment_sentiments.append({
            "polarity": c.sentiment.polarity,
            "subjectivity": c.sentiment.subjectivity
        })

    csa = sentiment.comment_sentiment_avg(comment_sentiments)
    csa.update({'submission_id': s.id})

    expected_keys = ['submission_id', 'polarity', 'subjectivity']
    assert sorted(csa.keys()) == sorted(expected_keys)

    assert isinstance(csa['polarity'], float)
    assert isinstance(csa['subjectivity'], float)
开发者ID:PsyBorgs,项目名称:redditanalyser,代码行数:30,代码来源:test_sentiment.py

示例12: add_comment

    def add_comment(name, email, comments, post_id):
        comment = Comment(post_id=post_id, name=name,
                          email=email, comments=comments)
        db.session.add(comment)
        db.session.commit()

        CommentService.inc_comments_count(post_id)

        return comment.to_dict()
开发者ID:guzhiyiai,项目名称:flask-blog,代码行数:9,代码来源:comment.py

示例13: handle

def handle(changeset):
    print ('Received ' + str(changeset))
    # Fetch project and pad ids.
    project_id = changeset['projectId']
    pad_id = changeset['padId']
    # Fetch project lock or create it, if not exists already.
    if project_id not in update_locks:
        update_locks[project_id] = Lock()
    update_lock = update_locks[project_id]
    with update_lock:
        # Fetch next revision number.
        if project_id not in revisions:
            revisions[project_id] = {}
        if pad_id not in revisions[project_id]:
            revisions[project_id][pad_id] = [Revision('0', None)]
        
        # Follow the changeset by all revisions not known by that user.
        revs = revisions[project_id][pad_id]
        apply_from = len(revs)
        for i in range(len(revs), 0, -1):
            if changeset['baseRev'] == revs[i - 1].id:
                apply_from = i
                break
        for i in range(apply_from, len(revs)):
            if changeset['baseLen'] == revs[i].changeset['newLen']:
                apply_from = i + 1
                break
        # Fetch current revision.
        crtRev, baseRev = changeset['revId'], changeset['baseRev']
        for i in range(apply_from, len(revs)):
            changeset = follow(revs[i].changeset, changeset)
        # Update base rev.
        changeset['baseRev'] = baseRev
        # Create new revision out of this changeset.
        revisions[project_id][pad_id].append(Revision(crtRev, changeset))
        # Update current pad in db.
        changeset['projectId'], changeset['padId'] = project_id, pad_id
        changeset['revId'] = crtRev
        updateDBPad(changeset, crtRev)
        # Add the new comments to DB.
        if 'comments' in changeset:
            for code, comment in changeset['comments'].items():
                newComment = Comment(comment['author'], comment['text'])
                newComment.pad_id = comment['padId']
                newComment.code = comment['code']
                db.session.add(newComment)
            db.session.commit()
        # Include the id of the client that generated the changeset.
        changeset['clientId'] = request.sid
        # Broadcast to all clients.
        emit('server_client_changeset', changeset, room=changeset['projectId'])
    # Send ACK to the client.
    emit('server_client_ack', changeset['padId'], room=request.sid)
开发者ID:JCGrant,项目名称:ColDE,代码行数:53,代码来源:socketio_server.py

示例14: event_show

def event_show(request, event_id):
    user = request.user
    event = Event.objects.get(pk=event_id)
    if request.method == 'POST':  # TODO: should really be PUT
        if user.get_profile().is_funder:
            grants = []
            for item in event.item_set.all():
                amount = request.POST.get("item_" + str(item.id), None)
                if amount:
                    amount = Decimal(amount)
                    grant, _ =\
                        Grant.objects.get_or_create(funder=user.get_profile(),
                                                    item=item,
                                                    defaults={'amount': 0})
                    amount_funded = sum(grant.amount for grant in
                                        Grant.objects.filter(item=item))
                    amount_funded += item.funding_already_received
                    # if the funder gave too much,
                    # adjust the price to be only enough
                    if amount + amount_funded - grant.amount > item.total:
                        amount = item.total - amount_funded + grant.amount
                    # only append if the amount has changed
                    if grant.amount != amount:
                        grant.amount = amount
                        grant.save()
                        grants.append(grant)
            if grants:
                messages.success(request, "Saved grant!")
                # email the event requester indicating that they've been funded
                event.status = 'F'  # F for FUNDED
                event.save()
                event.notify_requester(grants)
                # try to notify osa, but osa is not guaranteed to exist
                try:
                    user.get_profile().notify_osa(event, grants)
                except smtplib.SMTPException:
                    pass
            if request.POST.get('new-comment', None):
                comment = Comment(comment=request.POST['new-comment'],
                                  funder=user.get_profile(), event=event)
                comment.save()
            return redirect(EVENTS_HOME)
        else:
            return redirect(EVENTS_HOME)
    elif request.method == 'GET':
        if 'id' in request.GET:
            event.shared_funder = \
                User.objects.get(id=request.GET['id']).get_profile()
        return render_to_response('app/application-show.html',
                                  {'event': event},
                                  context_instance=RequestContext(request))
    else:
        return HttpResponseNotAllowed(['POST'])
开发者ID:JacobHenner,项目名称:common-funding-application,代码行数:53,代码来源:views.py

示例15: commit_comment

def commit_comment(request):
	user = User.objects.get(id = 1)
	aid = int(request.GET.get('id'))
	article = Article.objects.get(id = aid)
	nickname = request.GET.get('nickname')
	content = request.GET.get('content')
	if nickname == '':
		return HttpResponse("1")
	elif content == '':
		return HttpResponse("2")
	comment = Comment(user = user, article = article, nickname = nickname, content =content)
	comment.save()
	return HttpResponse('提交成功')
开发者ID:xueyue123,项目名称:zhBlog,代码行数:13,代码来源:front_manage.py


注:本文中的app.models.Comment类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。