Exemplo n.º 1
0
def test_validate():
    # should not raise any error
    User(name='totti', active=True, data=10).validate()

    user = User(name='totti', posts=4)
    with pytest.raises(ValidationError) as excinfo:
        user.validate()
    assert excinfo.value.as_dict() == {
        'posts': 'invalid value type'
    }

    comment = Comment(_id=ObjectId(), body='')
    with pytest.raises(ValidationError) as excinfo:
        comment.validate()
    assert excinfo.value.as_dict() == {
        'body': 'blank value is not allowed',
        'author': 'field is required'
    }

    post = Post(author=user, comments=[comment])
    with pytest.raises(ValidationError) as excinfo:
        post.validate()
    assert excinfo.value.as_dict() == {
        'title': 'field is required',
        'comments': {
            0: {
                'body': 'blank value is not allowed',
                'author': 'field is required'
            }
        }
    }
Exemplo n.º 2
0
    def test_parse_comments(self):

        response = '''{"response":[6,
            {"cid":2505,"uid":16271479,"date":1298365200,"text":"Добрый день , кароче такая идея когда опросы создаешь вместо статуса - можно выбрать аудитории опрашиваемых, например только женский или мужской пол могут участвовать (то бишь голосовать в опросе)."},
            {"cid":2507,"uid":16271479,"date":1286105582,"text":"Это уже не практично, имхо.<br>Для этого делайте группу и там опрос, а в группу принимайте тех, кого нужно.","reply_to_uid":16271479,"reply_to_cid":2505},
            {"cid":2547,"uid":2943,"date":1286218080,"text":"Он будет только для групп благотворительных организаций."}]}
            '''
        group = GroupFactory.create(remote_id=OWNER_ID)
        post = PostFactory.create(remote_id=TR_POST_ID, wall_owner=group)
        instance = CommentFactory.create(post=post)
        author = UserFactory.create(remote_id=16271479)
        instance.parse(json.loads(response)['response'][1])
        instance.save()

        self.assertEqual(instance.remote_id, '201164356_2505')
        self.assertEqual(instance.text, u'Добрый день , кароче такая идея когда опросы создаешь вместо статуса - можно выбрать аудитории опрашиваемых, например только женский или мужской пол могут участвовать (то бишь голосовать в опросе).')
        self.assertEqual(instance.author, author)
        self.assertTrue(isinstance(instance.date, datetime))

        instance = Comment(post=post)
        instance.parse(json.loads(response)['response'][2])
        instance.save()

        self.assertEqual(instance.remote_id, '201164356_2507')
        self.assertEqual(instance.reply_for.remote_id, 16271479)
Exemplo n.º 3
0
def api_create_comment(id):
    cookie_str = request.cookies.get(COOKIE_NAME)
    user = {}
    if cookie_str:
        user = cookie2user(cookie_str)
    if user is None:
        r=jsonify({'error':'Please signin first'})
        r.content_type = 'application/json'
        return r
    if not request.json['content'] or not request.json['content'].strip():
        r=jsonify({'error':'no content'})
        r.content_type = 'application/json'
        return r
    blog = Blog.query.filter(Blog.id==id).first()
    reprint = Reprint.query.filter(Reprint.id==id).first()
    b_id = ''
    if blog is not None:
        b_id = blog.id
    if reprint is not None:
        b_id = reprint.id
    if not b_id:
        r = jsonify({'error':'no blog'})
        r.content_type = 'application/json'
        return r
    comment = Comment(blog_id=b_id, user_id=user.id, user_name=user.name, user_image=user.image, content=request.json['content'].strip())
    db.session.add(comment)
    db.session.commit()
    a = comment.to_dict()
    r = jsonify(a)
    r.content_type = 'application/json;charset=utf-8'
    return r
Exemplo n.º 4
0
    def post(self, key):

        issue = db.get(key)

        name = self.request.get("name")
        email = self.request.get("email")
        text = self.request.get("comment")

        comment = Comment(
            name = name,
            email = email,
            comment = text,
            issue = issue,
        )
        comment.put()

        context = {
            'issue': issue,
        }

        # prepare the context for the template
        # calculate the template path
        path = os.path.join(os.path.dirname(__file__), 'templates',
            'issue.html')
        # render the template with the provided context
        self.response.out.write(template.render(path, context))
Exemplo n.º 5
0
def comment_add():
    log('发送评论')
    user_now = current_user()
    form = request.get_json()
    print('form, ', form)
    c = Comment(form)
    blog_id = form.get('blog_id', '')
    # 设置是谁发的
    c.sender_name = user_now.username
    c.blog = Blog.query.filter_by(id=blog_id).first()
    # 保存到数据库
    c.save()
    blog = c.blog
    blog.com_count = len(Comment.query.filter_by(blog_id=blog.id).all())
    blog.save()
    log('写评论')
    status = {
        'content': c.content,
        'sender_name': c.sender_name,
        'created_time': formatted_time(c.created_time),
        'id': c.id,
    }
    r = json.dumps(status, ensure_ascii=False)
    print('r, ', r)
    return r
Exemplo n.º 6
0
def add_comment(request, movie_id):
    newcomment = Comment(text=request.POST['comment_text'], movie=Movie.objects.filter(id=movie_id)[0])        
    newcomment.save()
    comments = Comment.objects.filter(movie=movie_id)
    movie = Movie.objects.filter(id=movie_id)[0]
    context = {'comments':comments,'movie':movie}
    return render(request, 'movies/movie.html', context)
Exemplo n.º 7
0
 def get(self):
     post_id = int(self.request.get('id'))
     post = Post.get_by_id(post_id)
     post.comment += 1
     post.put()
     comment = Comment(post=post.key, content=self.request.get("content"))
     comment.put()
Exemplo n.º 8
0
def product_page(request, product_id):
    product = Product.objects.get(pk=product_id)
    product = get_object_or_404(Product, pk=product_id)

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            author_name = form.cleaned_data.get("author_name") or u"Гость"
            body = form.cleaned_data.get("body")
            c = Comment(author_name=author_name,
                        body=body,
                        product=product)
            c.save()
            return HttpResponseRedirect('/product/' + product_id)
    else:
        form = CommentForm()

    categories = get_categories()
    comments = product.comment_set.all().order_by('-date')[:10]
    bread_categories = [MainMock()] + product.category.get_path_up()
    print(bread_categories)

    context_dict = dict(product=product,
                        categories=categories,
                        comments=comments,
                        form=form,
                        cart=get_cart(request),
                        bread_categories=bread_categories,
                        )

    return render(request, 'store/product.html', context_dict)
Exemplo n.º 9
0
 def post(self):
     photo_id = int(self.request.get('pid'))
     Author = self.request.get('comment-name')
     comment = self.request.get('comment')
     photo = Image.get_Detail(photo_id)
     logging.error("Author is" + Author)
     logging.error(comment)
     if Author == '' or comment == '':
         pic_id = "/Home#" + str(photo_id)
         self.redirect(pic_id)
     else:
         if photo:
             try:
                 comment = Comment(
                     Author=Author,
                     Comment=comment, Image=photo.key)
                 comment.put()
                 logging.info("Horray, a comment is saved.")
             except:
                 logging.error("Error saving comment in datastore.")
             finally:
                 pic_id = "/Home#" + str(photo_id)
                 render = template.render('templates/redirect.html',
                                          {'link': pic_id, 'message': 'Commented'})
                 self.response.write(render)
Exemplo n.º 10
0
def add_comment(post_id):
    comment = Comment(request.form['text'])
    comment.author_id = current_user().id
    comment.post_id = post_id
    db.session.add(comment)
    db.session.commit()
    return redirect('/post/' + str(post_id))
Exemplo n.º 11
0
    def get(self):
        # see if there is a key
        comment = None
        status = None
        try:
            comment = Comment.get( self.request.get('key') )
            status = self.request.get('status')
        except db.BadKeyError:
            pass

        if comment is None:
            # show all the 'new' comments
            comments = Comment.all().filter('status =', 'new').order('inserted').fetch(page_count+1)
            more = True if len(comments) > page_count else False
            comments = comments[:page_count]
            vals = {
                'comments' : comments,
                'more'     : more,
                }
            self.template( 'comment-list.html', vals, 'admin' )
        else:
            comment.status = status_map[status]
            comment.put()
            comment.node.regenerate()
            self.redirect('./')
            return
Exemplo n.º 12
0
def newcomment(request, blog_id):
    if request.user.is_authenticated():
        comment = Comment(comment=request.POST.get('comment'), blog=Blog(pk=blog_id) )
        comment.save()
        return HttpResponseRedirect(reverse('Blog:main'))
    else:
        return HttpResponse("You are not logged in.")
    def test_parse_comment(self):

        response = u'''{"attrs": {"flags": "l,s"},
            "author_id": "538901295641",
            "date": "2014-04-11 12:53:02",
            "id": "MTM5NzIwNjM4MjQ3MTotMTU5NDE6MTM5NzIwNjM4MjQ3MTo2MjUwMzkyOTY2MjMyMDox",
            "like_count": 123,
            "liked_it": false,
            "reply_to_comment_id": "MTM5NzIwNjMzNjI2MTotODE0MzoxMzk3MjA2MzM2MjYxOjYyNTAzOTI5NjYyMzIwOjE=",
            "reply_to_id": "134519031824",
            "text": "наверное и я так буду делать!",
            "type": "ACTIVE_MESSAGE"}'''
        comment = CommentFactory(id='MTM5NzIwNjMzNjI2MTotODE0MzoxMzk3MjA2MzM2MjYxOjYyNTAzOTI5NjYyMzIwOjE=')
        author = UserFactory(id=134519031824)
        discussion = DiscussionFactory()
        instance = Comment(discussion=discussion)
        instance.parse(json.loads(response))
        instance.save()

        self.assertEqual(instance.id, 'MTM5NzIwNjM4MjQ3MTotMTU5NDE6MTM5NzIwNjM4MjQ3MTo2MjUwMzkyOTY2MjMyMDox')
        self.assertEqual(instance.object_type, 'ACTIVE_MESSAGE')
        self.assertEqual(instance.text, u"наверное и я так буду делать!")
        self.assertEqual(instance.likes_count, 123)
        self.assertEqual(instance.liked_it, False)
        self.assertEqual(instance.author, User.objects.get(pk=538901295641))
        self.assertEqual(instance.reply_to_comment, comment)
        self.assertEqual(instance.reply_to_author, User.objects.get(pk=134519031824))
        self.assertTrue(isinstance(instance.date, datetime))
        self.assertTrue(isinstance(instance.attrs, dict))
Exemplo n.º 14
0
def add(request):
    redirect_to=COMMENT_REDIRECT_TO
    if request.POST:
        form=CommentForm(request.POST)
        if form.is_valid():
            if 'redirect' in form.cleaned_data:
                redirect_to=form.cleaned_data['redirect']
            else:
                redirect_to=COMMENT_REDIRECT_TO

            if not request.user.is_authenticated():
                msg = _("In order to post a comment you should have a friendsnippets account.")
                msg = urlquote_plus(msg)
                if COMMENT_SIGNIN_VIEW:
                    redirect_to=reverse(COMMENT_SIGNIN_VIEW) + "?next=" + redirect_to + "&msg=" + msg
                else:
                    redirect_to='/'
                if not request.user.is_authenticated():
                    return HttpResponseRedirect(redirect_to)   
            
            try:    
                content_type=ContentType.objects.get(id=form.cleaned_data['content_type'])
            except:
                pass
            if content_type:
                params = {
                    'headline':form.cleaned_data['headline'],
                    'comment':form.cleaned_data['comment'],
                    'user':request.user,
                    'content_type':content_type,
                    'object_id':form.cleaned_data['object_id'],
                }
                c = Comment(**params)
                c.save()
    return HttpResponseRedirect(redirect_to)    
Exemplo n.º 15
0
def show_aloj_id(request,ide):
    pathf=request.path+"/xmlfrances"
    pathi=request.path+"/xmlingles"
    try:
        hotel=Hotel.objects.get(id=ide)
        print hotel.stars
        print hotel.tipo
    except Hotel.DoesNotExist:
            context={'name': ""}
            return render_to_response('alojid.html',context);
    listimages=Image.objects.filter(hid=hotel.id)
    listcoms=""
    if request.method =='POST':
        value = request.POST.get('comentarios', "")

        n= hotel.numbercom+1;
        hotel.numbercom=n
        hotel.save()
        comment=Comment(hid=hotel.id,com=hotel,text=value)
        comment.save()
    listcoms=Comment.objects.filter(hid=hotel.id)
    
    try:
        us=PagUser.objects.get(user=request.user.username)
    except PagUser.DoesNotExist:
        context = {'lista':listimages[0:5],'condicion':"",'url':hotel.url,'name':hotel.name,'address':hotel.address,'body':hotel.body,'comentarios':listcoms,'type':hotel.tipo,'stars':hotel.stars,'pathf':pathf,'pathi':pathi,'id':ide,'email':hotel.email,
                    'phone':hotel.phone}
        return render_to_response('alojid.html', context,context_instance = RequestContext(request))
    context = {'lista':listimages[0:5],'condicion':"",'url':hotel.url,'name':hotel.name,'address':hotel.address,'body':hotel.body,'comentarios':listcoms,'type':hotel.tipo,'stars':hotel.stars,'pathf':pathf,'pathi':pathi,'id':ide,'email':hotel.email,
                'phone':hotel.phone,'color':us.color,'size':us.size}
    return render_to_response('alojid.html', context,context_instance = RequestContext(request))
Exemplo n.º 16
0
  def post(self, post_id):
    session = get_current_session()
    if session.has_key('user'):
      message = helper.sanitizeHtml(self.request.get('message'))
      user = session['user']
      key = self.request.get('comment_key')
      if len(message) > 0 and key == keys.comment_key:
        try:
          post = Post.all().filter('nice_url =', helper.parse_post_id( post_id ) ).get()
          if post  == None: #If for some reason the post doesn't have a nice url, we try the id. This is also the case of all old stories
            post = db.get( helper.parse_post_id( post_id ) ) 

          post.remove_from_memcache()
          comment = Comment(message=message,user=user,post=post)
          comment.put()
          helper.killmetrics("Comment","Root", "posted", session, "",self)
          vote = Vote(user=user, comment=comment, target_user=user)
          vote.put()
          Notification.create_notification_for_comment_and_user(comment,post.user)
          self.redirect('/noticia/' + post_id)
        except db.BadKeyError:
          self.redirect('/')
      else:
        self.redirect('/noticia/' + post_id)
    else:
      self.redirect('/login')
Exemplo n.º 17
0
 def test_comment_approved(self):
     post = Post(author=self.me, title="Hi", created_date=timezone.now())
     post.save()
     comment = Comment(author=self.me.username, post=post)
     comment.approve()
     comment.save()
     assert comment in post.approved_comments()
Exemplo n.º 18
0
    def createComment(self, request):
        """Create new Comment object, returning CommentForm/request."""
        
        author = self._getAuthorFromUser()
        data['authorName'] = author.displayName
        data['authorID'] = author.authorID

        self._checkComment(request)

        data = {'comment': request.comment}

        # get the article key for where the comment will be added
        article_key = self._checkKey(request.websafeArticleKey, 'Article')

        comment_id = Comment.allocate_ids(size=1, parent=article_key)[0]
        comment_key = ndb.Key(Comment, comment_id, parent=article_key)
        data['key'] = comment_key

        # create Comment
        comment_key = Comment(**data).put()

        # send alerts to all authors of Article and all other comments
        #taskqueue.add(params={'email': author.mainEmail,
        #    'CommentInfo': repr(request)},
        #    url='/tasks/send_comment_alert'
        #)

        return self._copyCommentToForm(comment_key.get(), article_key=article_key, author=author)
Exemplo n.º 19
0
def submit_comment_view(request):
    try:
        if request.method == 'GET':
            paper_id = int(request.GET['id'])
        elif request.method == 'POST':
            paper_id = int(request.POST['id'])
        paper = Paper.objects.filter(id=paper_id).get()
        comment = Comment()
        comment.paper = paper
        comment.user = request.user
        if request.method == 'POST':
            form = forms.SubmitCommentForm(request.POST, instance=comment)
            if form.is_valid():
                form.save(paper)
                return HttpResponseRedirect("paper?id=%d" % paper_id)
        else:
            form = forms.SubmitCommentForm()
    except (ValueError, KeyError, Paper.DoesNotExist):
        paper = None
        form = None

    return render_to_response("submit_comment.html", RequestContext(request, {
        'form' : form,
        'paper' : paper,
    }))
Exemplo n.º 20
0
    def delete_post(cls, post_id, user_id):
        error_msg = None
        posts = Post.all().order('-created').fetch(limit=10)
        updated_post_list = posts
        post = Post.get_by_id(post_id)
        if user_id == post.created_by:

            # delete comments of the post
            comments = Comment.all().filter('post_id =', post_id).fetch(limit=10)
            for c in comments:
                Comment.delete(c)

            # delete likes of the post
            likes = Like.all().filter('post_id =', post_id).fetch(limit=10)
            for l in likes:
                Like.delete(l)

            # delete the post
            updated_post_list = cls.update_list_on_delete(
                object_list=posts,
                object_id=post_id
            )
            Post.delete(post)

        else:
            error_msg = 'You can delete only your own posts'

        return updated_post_list, error_msg
Exemplo n.º 21
0
def post_comment(request):

    user = request.POST.get('user')
    content = request.POST.get('content')
    email = request.POST.get('email')
    blog_id = request.POST.get('blog_id')
    quote = request.POST.get("quote", "").split("###")

    #过滤content里面的JS字符
    content = content.replace("<", "&lt;").replace(">", "&gt; ")

    blog = get_object_or_404(Article, pk=blog_id)
    if len(quote) == 3 and \
        Comment.objects.filter(pk=quote[2]):
        content = u"""
        <p>
        引用来自<code>%s楼-%s</code>的发言
        </p>""" % (quote[0], quote[1]) + content

    comment = Comment(
        article=blog,
        email=email,
        name=user, 
        content=content)
    comment.save()

    return HttpResponse("%d" % comment.id)
Exemplo n.º 22
0
def add_comment(request, movie_id):
    Cmovie = Movie.objects.filter(pk=movie_id)[0]
    newcomment = Comment(text=request.POST['comment_text'], movie=Cmovie)
    # when making new objects, always remember to save them
    newcomment.save()
    return HttpResponseRedirect('/movies/' + movie_id)
    
def random_comment(blog_post):
    possible_comments = [
        'Wow cool!',
        'Neato!',
        'Lame.',
        'First post!',
        'Was on Reddit yesterday.',
        'Pics or didn\'t happen.',
        'tl;dr was awesome',
        'I was so sad today, this made me laugh so much thanks lol.',
        'Do you think they care?',
        'Do you believe in life after love?',
        'I like this version better.',
        'That was just great.',
        'Upvoting because after reading your username, I\'m pretty sure you\'re trolling.',
        'Lol. I saw this one first and was a bit confused.',
        'I laughed so much!',
        'This is awesome',
        'Windows XP is the Playstation 2 of Operating Systems.',
        'I think we\'ve all been there at one point'
    ]

    ts = datetime.now() + timedelta(days=-random.randint(1, 50))
    c = Comment(content=possible_comments[random.randint(0, len(possible_comments)-1)], timestamp=ts, blog_post=blog_post.key)
    c.put()
Exemplo n.º 24
0
def review_comment():
    commid = request.json['commid']
    review = request.json['review']
    user = User.current()
    if not user.anonymous:
        Comment.approve(commid, review, user)
    return jsonify(success=True)
Exemplo n.º 25
0
def submit_comment_view(request):
    import forms
    user = UserProfile.objects.get(username=request.user.username)

    try:
        if request.method == 'GET':
            paper_id = int(request.GET['id'])
        elif request.method == 'POST':
            paper_id = int(request.POST['id'])
        paper = Paper.objects.filter(id=paper_id).get()
        comment = Comment()
        comment.paper = paper
        comment.user = user
        if request.method == 'POST':
            form = forms.SubmitCommentForm(request.POST, instance=comment)
            if form.is_valid():
                form.save(paper)
                return HttpResponseRedirect("paper?id=%s" % paper_id)
        else:
            form = forms.SubmitCommentForm()
    except (ValueError, KeyError, Paper.DoesNotExist):
        paper = None
        form = None

    return render(request, "submit_comment.html", {
        'form' : form,
        'paper' : paper,
        'which_page' : "submit_comment"
    })
Exemplo n.º 26
0
def post_comment(text, author, suggestion):
	brtext = text.replace('\n', '<br/>')
	comment = Comment(text=brtext, author=author, suggestion=suggestion)
	comment.put()
	author.lastposted = date.today()
	author.put()
	notify_comment(text, comment)
Exemplo n.º 27
0
    def _post_comment(self, index_url, comment_str, auther_ip, user):
        title=urlparse(index_url).netloc
        
        print comment_str, user
        logger.debug('Auther_ip:' + auther_ip
                     + ' User:'******' Title:' + title
                     + ' Index_url:' + index_url
                     + ' Comment_str:' + comment_str)

        comment_board, created = CommentBoard.objects.get_or_create(
                                    url=index_url,
                                    title=urlparse(index_url).netloc)
        comment_board.save() if created else None
        if user.is_authenticated():
            comment = Comment(
                    time_added=datetime.datetime.utcnow().replace(
                                    tzinfo=utc),
                    comment_str=comment_str,
                    comment_board=comment_board,
                    auther_ip=auther_ip,
                    user=user) # 以后换成auther,现在先用user
        else:
            '''
            Annoymous User access the site.
            '''
            comment = Comment(
                    time_added=datetime.datetime.utcnow().replace(
                                    tzinfo=utc),
                    comment_str=comment_str,
                    comment_board=comment_board,
                    auther_ip=auther_ip)
        comment.save()
Exemplo n.º 28
0
def teamProfile(teamId):
	if current_user.team:
		if int(teamId) == int(current_user.team_id):
			return redirect(url_for('team_page'))
	form = CommentForm()
	team = db.session.query(Team).filter(Team.id == teamId).first()
	comments = db.session.query(Comment).filter(Comment.idea_id == team.idea.id).all()

	if not team:
		flash('Team '+teamId+' not found.', 'error')
		return redirect(url_for('home'))
	else:
		if form.validate_on_submit():
			comment = Comment()
			comment.content = form.comment.data
			team.idea.comment.append(comment)
			current_user.comment.append(comment)
			db.session.add(comment)

			for member in comment.idea.team.members:
				notif = PersonalNotification()
				notif.content = current_user.username + " commented on your team's idea."
				member.notification.append(notif)

			db.session.commit()
			return render_template('team_view.html', form=form, team=team, comments=comments)

		return render_template('team_view.html', form=form, team=team, comments=comments)
Exemplo n.º 29
0
    def execute(self):
        invite_attendee = None
        if self.invite_attendee_id:
            invite_attendee = InviteAttendee.get_by_unique_id(
                self.invite_attendee_id
            )

        invite = Invite.get_by_unique_id(self.invite_unique_id)

        if invite is None:
            raise InviteNotFoundException()

        author = None
        if invite_attendee is not None:
            author = invite_attendee.name or invite_attendee.email or invite_attendee.phone

        if invite.comments is None:
            invite.comments = []

        comment = Comment()
        comment.author = author
        comment.comment = self.comment
        comment.commented_on = datetime.datetime.now()
        invite.comments.append(comment)
        invite.put()

        return comment
Exemplo n.º 30
0
 def get(self):
     params = self.request.url_params
     print params
     category = params[0]
     which = params[1]
     article, comment, comments, user = None, None, None, None
     if category == 'article':
         # delete article and all related comments
         old_article = Article.select_one('created_at=?', which)
         article = old_article
         old_article.delete()
         old_comments = Comment.select_all('article_id=?', article.id)
         comments = old_comments
         if old_comments:
             for comment in old_comments:
                 comment.delete()
     elif category == 'user':
         old_user = User.select_one('id=?', which)
         user = old_user
         old_user.delete()
     elif category == 'comment':
         old_comment = Comment.select_one('id=?', which)
         comment = old_comment
         old_comment.delete()
     return self.render('_delete.html', article=article, comment=comment, \
             comments=comments, user=user)
Exemplo n.º 31
0
    def post(self, request, **kwargs):

        status, aoi = self._get_aoi_and_update(self.kwargs.get('pk'))

        if aoi.user_can_complete(request.user):
            aoi = self._update_aoi(request, aoi, status)
            Comment(aoi=aoi,
                    user=request.user,
                    text='changed status to %s' % status).save()

            features_updated = 0
            if 'feature_ids' in request.POST:
                features = request.POST['feature_ids']
                features = str(features)
                if features and len(features):
                    try:
                        feature_ids = tuple(
                            [int(x) for x in features.split(',')])
                        feature_list = Feature.objects.filter(
                            id__in=feature_ids)
                        features_updated = feature_list.update(status=status)
                    except ValueError:
                        features_updated = 0

            # send aoi completion event for badging
            send_aoi_create_event(request.user, aoi.id,
                                  aoi.features.all().count())
            return HttpResponse(json.dumps({
                aoi.id: aoi.status,
                'features_updated': features_updated
            }),
                                mimetype="application/json")
        else:
            error = dict(
                error=403,
                details="User not allowed to modify the status of this AOI.",
            )
            return HttpResponse(json.dumps(error), status=error.get('error'))
Exemplo n.º 32
0
def entry_comments_api(entry_id=0):
    comments = list(Comment.select().where(
        Comment.entry_id == entry_id).order_by(Comment.t).dicts())
    likes = list(Like.select().where(Like.entry_id == entry_id).dicts())

    uids = list(
        set([c['authorId'] for c in comments] + [l['uid'] for l in likes]))
    users = dict()
    for u in User.select().where(User.uid.in_(uids)).dicts():
        users[u['uid']] = {'name': u['name'], 'headPic': u['headPic']}

    for like in likes:
        like['name'] = users.get(like['uid'], {}).get('name', '')
        like['headPic'] = users.get(like['uid'], {}).get('headPic', '')

    for comment in comments:
        comment['headPic'] = users.get(comment['authorId'],
                                       {}).get('headPic', '')

    ret = dict(comments=comments, likes=likes, users=users)
    if request.path.split('/')[1] == 'comments':
        return jsonify(ret)
    return ret
Exemplo n.º 33
0
async def api_create_comment(id, request, *, content):
    '''
    在blog详情页创建评论保存(api)
    :param id:
    :param request:
    :param content:
    :return:
    '''
    # 已登录用户才有权限评论blog
    check_signin(request)
    user = request.__user__
    if not content or not content.strip():
        raise APIValueError('content', '请输入评论内容!')
    blog = await Blog.findById(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
Exemplo n.º 34
0
async def api_create_comment(id, request, *, content):
    """
    添加评论
    :param id:
    :param request:
    :param content:
    :return:
    """
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first.')
    if not content or not content.strip():
        raise APIValueError('content')
    blog = await 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())
    await comment.save()
    return comment
Exemplo n.º 35
0
    def get(self, post_id):
        if self.good_cookie_exists():
            # get user name from cookie
            h = self.request.cookies.get('user')
            curuser = h.split("|")[0]
            comments = Comment.all().filter('post_id =', post_id)

            # get post subject from Post table using post_id for
            # display at top of page
            key = db.Key.from_path('Post', int(post_id))
            p = db.get(key)
            if not p:
                self.redirect("/")
                return
            subject = p.subject
            self.render("comments.html",
                        comments=comments,
                        post_id=post_id,
                        curuser=curuser,
                        subject=subject)
        else:
            self.redirect("/login")
            return
Exemplo n.º 36
0
def comment():
	comment_form = forms.CommentForm(request.form)
	
	if request.method == 'POST' and comment_form.validate(): #to validate forms inputs. We also had to add it in _macro.html, in the list {{field.errors}}
		'''print(comment_form.username.data)
		print(comment_form.email.data)
		print(comment_form.comment.data)
	else:
		print ("Error in the form!!")'''


		user_id = session['user_id'] #since we work with cookies, this is the way to get the user_id
		comment = Comment(user_id = user_id, 
						  text = comment_form.comment.data)

		print(comment)
		db.session.add(comment)
		db.session.commit()
		success_message = "New comment created"
		flash(success_message)

	title = "Flask Course"
	return render_template('comment.html', title = title, form = comment_form)
Exemplo n.º 37
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)
    def post(self, post_id):
        """
        post:   Post
        Args:
                self:   This object
                post_id:    Post ID
        """
        if not self.user:
            return self.redirect('/login')

        b = Post.get_by_id(int(post_id), parent=blog_key())
        #
        #       Check that user IDs match
        #
        user_id = self.user.key().id()
        if b.user_id != user_id:
            return self.redirect('/blog/%s' % str(b.key().id()))
        b.delete()
        comments = Comment.all().filter('post_id =', post_id)
        for comment in comments:
            comment.delete()

        self.redirect('/blog/postdeleted')
Exemplo n.º 39
0
    def post(self, thread_name):
        '''Add a comment to thread.'''
        args, author_name = parse_and_decode()

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

        # Get thread (add if needed)
        try:
            thread = (db.session.query(Thread)
                      .filter(Thread.name == thread_name).one())
        except NoResultFound:
            thread = Thread(name=thread_name)
            db.session.add(thread)
            db.session.commit()

        author_id = get_author_add_if_needed(author_name)

        now = arrow.utcnow()
        comment = Comment(author_id=author_id, text=text, thread_id=thread.id,
                          created=now, modified=now)
        db.session.add(comment)
        db.session.commit()
        return get_thread_comments(thread)
Exemplo n.º 40
0
def get_single_comment(id):
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()
        db_cursor.execute(
            """
        SELECT  
            c.id,
            c.post_id,
            c.author_id,
            c.content,
            c.created_on,
            u.username username
        FROM Comments c
        JOIN Users u
            ON u.id = c.author_id
        WHERE c.id = ?
        """, (id, ))
        data = db_cursor.fetchone()
        comment = Comment(data['id'], data['post_id'], data['author_id'],
                          data['content'], data['created_on'],
                          data['username'])
        return json.dumps(comment.__dict__)
Exemplo n.º 41
0
def comment():
    #Aqui llamaos a la clase forms.CommentForm() q tiene nuestro archivo
    #Ahora si nuestra tambien si viene algun tipo de tados creamos una instancia con eso tipo de datos
    #Para luego verlos en nuestros inputs
    comment_form = forms.CommentForm(request.form)

    #Aqui sencillamente lo q se hace es q si el method es Post mostramos los datos nuestro formulario
    if request.method == "POST" and comment_form.validate():
        user_id = session["user_id"]
        comment = Comment(
            user_id=user_id,
            text=comment_form.comment.data,
        )

        db.session.add(comment)
        db.session.commit()

        success_message = "Nuevo Comentario Creado Satifactoriamente!"
        flash(success_message)
    else:
        print("Error En El Formulario!.")
    title = "Curso Flask| Formulario De Comentarios"
    return render_template("comment.html", title=title, form=comment_form)
def get_single_comment(id):
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """
	    SELECT
            c.id,
            c.commentSubject,
            c.commentBody,
            c.userId,
            c.postId
        FROM Comment c
        WHERE c.id = ?
        """, (id, ))

        data = db_cursor.fetchone()

        comment = Comment(data['id'], data['commentSubject'],
                          data['commentBody'], data['userId'], data['postId'])

        return json.dumps(comment.__dict__)
Exemplo n.º 43
0
async def api_create_comment(id, request, *, content):
    # 对某个博客发表评论
    user = request.__user__
    # 必须为登陆状态下,评论
    if user is None:
        raise APIPermissionError('content')
    # 评论不能为空
    if not content or not content.strip():
        raise APIValueError('content')
    # 查询一下博客id是否有对应的博客
    blog = await 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())
    # 保存到评论表里
    await comment.save()
    return comment
Exemplo n.º 44
0
def comment_delete():
    data = request.get_json()

    id = data.get('id')

    comment = Comment.find_by_pk(id)

    if comment:
        try:
            comment.topic.update_comment_count(offset=-1)
            comment.topic.update_user_comment_count(offset=-1,
                                                    user_id=comment.user_id)
            comment.delete()
            db_session.commit()

            cache.update_topic(comment.topic.id, comment.topic)
            cache.update_sorted_topics(comment.topic, 'comment_count')
            return json_data(data)
        except Exception:
            db_session.rollback()
            return json_error_database()
    else:
        return json_error_invalid_request()
Exemplo n.º 45
0
    def get(self, post_id):

        k = db.Key.from_path('Comment', int(post_id), parent=blog_key())
        c = db.get(k)

        if not c:
            self.error(404)
            return

        if self.user and (self.user.key() == c.comment_user.key()):
            self.render("deletepage.html", comment=c.content)

        elif self.user and (self.user.key() != c.comment_user.key()):
            error = "You can only delete comments you created"
            posts = greetings = Post.all().order('-created')
            comments = Comment.all().order('-created')
            self.render('front.html',
                        posts=posts,
                        comments=comments,
                        error=error)

        else:
            self.redirect('/login')
    def get(self, comment_id):
        """
        get:   Get
        Args:
                self:   This object
                comment_id:    Comment ID
        """
        c = Comment.get_by_id(int(comment_id), parent=blog_key())

        if not c:
            self.render('notfound.html')
            return
#
#       Check that user IDs match
#
        user_id = self.user.key().id()
        if c.user_id != user_id:
            self.redirect('/blog/comment/%s' % str(c.key().id()))

        content = c.content
        self.render('deletecomment.html',
                    content=content,
                    comment_id=comment_id)
Exemplo n.º 47
0
Arquivo: blog.py Projeto: wing1000/wb3
    def get(self, direction='next', page='2', base_id='1'):
        if page == '1':
            self.redirect(BASE_URL)
            return
        objs = Article.get_page_posts(direction, page, base_id)
        if objs:
            if direction == 'prev':
                objs.reverse()
            fromid = objs[0].id
            endid = objs[-1].id
        else:
            fromid = endid = ''

        allpost = Article.count_all_post()
        allpage = allpost / EACH_PAGE_POST_NUM
        if allpost % EACH_PAGE_POST_NUM:
            allpage += 1
        output = self.render(
            'index.html', {
                'title': "%s - %s | Part %s" %
                (SITE_TITLE, SITE_SUB_TITLE, page),
                'keywords': KEYWORDS,
                'description': SITE_DECR,
                'objs': objs,
                'cats': Category.get_all_cat_name(),
                'tags': Tag.get_hot_tag_name(),
                'page': int(page),
                'allpage': allpage,
                'listtype': 'index',
                'fromid': fromid,
                'endid': endid,
                'comments': Comment.get_recent_comments(),
                'links': Link.get_all_links(),
            },
            layout='_layout.html')
        self.write(output)
        return output
Exemplo n.º 48
0
def post_recovery(database_entry, requested_post):
    try:
        if current_user.email != requested_post["author_email"] \
                or current_user.author is False and current_user.admin is False:
            return abort(403)
    except AttributeError:
        return abort(401)
    except KeyError:
        return abort(400)
    comments = requested_post["comments"]
    new_post = BlogPost(
        author=User.query.filter_by(
            email=requested_post["author_email"]).first(),
        title=requested_post["post_title"],
        subtitle=requested_post["subtitle"],
        date=requested_post["date"],
        body=requested_post["body"],
        img_url=requested_post["img_url"],
    )
    db.session.add(new_post)
    for comment in comments:
        new_comment = Comment(
            author=User.query.filter_by(email=comment["author_email"]).first(),
            parent_post=new_post,
            comment=comment["comment"],
            date=comment["date"])
        db.session.add(new_comment)
        for reply in comment["replies"]:
            new_reply = Reply(author=User.query.filter_by(
                email=reply["author_email"]).first(),
                              parent_comment=new_comment,
                              reply=reply["reply"],
                              date=reply['date'])
            db.session.add(new_reply)
    db.session.delete(database_entry)
    db.session.commit()
    return redirect(url_for('home.home_page'))
Exemplo n.º 49
0
def movie_detail(movie_id):
    movie = Movie.query.filter_by(brief_id=movie_id).first()
    if request.method == 'POST':
        print(request.form.get('comment'))
        comment = request.form.get('comment')
        u = User.query.filter_by(id=current_user.get_id()).first()

        c = Comment(
            user=u,
            movie=movie,
            comment_time=datetime.datetime.now(),
            content=comment,
            point=5,
        )
        db.session.add(c)
        db.session.commit()

    comments = movie.comments.all()

    can_watched = False
    if current_user.is_authenticated:
        consume_records = ConsumeRecord.query.filter_by(
            consumer=current_user).all()
        bought_moveis = [record.movie for record in consume_records]
        if movie in bought_moveis:
            can_watched = True

    if not movie:
        abort(404)

    return render_template(
        'movie_detail.html',
        movie=movie,
        user=current_user,
        comments=comments,
        can_watched=can_watched,
    )
Exemplo n.º 50
0
    def post(self, user, post_key, comment_id):
        """Handle Post Comments requests."""
        data = json.loads(self.request.body)
        reply_data = data['replyData']
        post = ndb.Key(urlsafe=post_key).get()
        institution = post.institution.get()

        Utils._assert(not institution.is_active(),
                      "This institution is not active", NotAuthorizedException)
        Utils._assert(post.state == 'deleted', "This post has been deleted",
                      EntityException)

        reply = Comment.create(reply_data, user)
        post.reply_comment(reply, comment_id)

        notification_message = post.create_notification_message(
            user_key=user.key,
            current_institution_key=user.current_institution,
            sender_institution_key=post.institution)
        notification_type = 'COMMENT'

        if (post.author != user.key):
            send_message_notification(receiver_key=post.author.urlsafe(),
                                      notification_type=notification_type,
                                      entity_key=post.key.urlsafe(),
                                      message=notification_message)

        comment = post.get_comment(comment_id)
        notification_type = "REPLY_COMMENT"

        if (comment.get('author_key') != user.key.urlsafe()):
            send_message_notification(receiver_key=comment.get('author_key'),
                                      notification_type=notification_type,
                                      entity_key=post.key.urlsafe(),
                                      message=notification_message)

        self.response.write(json.dumps(Utils.toJson(reply)))
Exemplo n.º 51
0
 def get(self, post_id):
     session = get_current_session()
     if session.has_key('user'):
         user = session['user']
     try:
         post = db.get(helper.parse_post_id(post_id))
         comments = Comment.all().filter(
             "post =", post.key()).order("-karma").fetch(1000)
         comments = helper.order_comment_list_in_memory(comments)
         prefetch.prefetch_comment_list(comments)
         display_post_title = True
         prefetch.prefetch_posts_list([post])
         if helper.is_json(post_id):
             comments_json = [
                 c.to_json() for c in comments if not c.father_ref()
             ]
             if (self.request.get('callback')):
                 self.response.headers[
                     'Content-Type'] = "application/javascript"
                 self.response.out.write(
                     self.request.get('callback') + '(' +
                     simplejson.dumps({
                         'post': post.to_json(),
                         'comments': comments_json
                     }) + ')')
             else:
                 self.response.headers['Content-Type'] = "application/json"
                 self.response.out.write(
                     simplejson.dumps({
                         'post': post.to_json(),
                         'comments': comments_json
                     }))
         else:
             self.response.out.write(
                 template.render('templates/post.html', locals()))
     except db.BadKeyError:
         self.redirect('/')
Exemplo n.º 52
0
    def post(self, share_key, comment_id):
        shared_file = models.Sharedfile.get_by_share_key(share_key)
        user = self.get_current_user_object()
        comment = Comment.get("id=%s", comment_id)

        if not shared_file or not comment:
            raise tornado.web.HTTPError(404)

        existing_comment_like = models.CommentLike.get("comment_id = %s and user_id = %s",
                comment.id, user.id)

        if existing_comment_like:
            existing_comment_like.deleted = 1
            existing_comment_like.save()

        json = self.get_argument("json", False)
        if json:
            self.set_header("Cache-Control","no-store, no-cache, must-revalidate");
            self.set_header("Pragma","no-cache");
            self.set_header("Expires", 0);
            count = models.CommentLike.where_count("comment_id = %s", comment.id)
            return self.write(json_encode({'response':'ok', 'count': count, 'like' : True }))
        else:
            return self.redirect("/p/%s?salty" % (share_key,))
Exemplo n.º 53
0
def commentInfoUpdate():
    values = request.values
    comment_body = values.get('comment')
    comment_since = values.get('comment_since')
    token = request.headers.get('token','')
    postid = values.get('postid')
    if not token:
        return jsonify({
            'code':-1,
            'errmsg':'illegal token'
        })
    u = getUserbyToken(token)
    if u is None:
        return jsonify({
            'code':-1,
            'errmsg':'illegal token'
        })
    a = Article.query.get(postid)
    app.logger.info('article id:: {}'.format(a.id))
    if a is None:
        return jsonify({
            'code':-1,
            'errmsg':'illegal token'
        })

    c = Comment(comment=comment_body,comment_since=comment_since)
    db.session.add(c)
    u.comments.append(c)
    a.comments.append(c)
    a.comment_num += 1
    # c.user = u
    db.session.commit()
    return jsonify({
        'code':1,
        'msg':'add a comment successfully'
    })
Exemplo n.º 54
0
    def update_existing_submissions_comments(self):
        for submission in Submission.objects:
            last_comment = Comment.objects(
                submission_id=submission.id).order_by('timestamp').first()
            if last_comment:
                reddit_submission = self.reddit.submission(submission.id)
                try:
                    reddit_submission.author
                # submission was deleted
                except prawcore.exceptions.NotFound:
                    logging.error('Submission %s was deleted', submission.id)
                    continue
                except prawcore.exceptions.Forbidden:
                    logging.error('Access restricted for submission %s',
                                  submission.id)
                    continue
                except Exception as exc:
                    logging.error(exc.message)
                    continue

                self.read_submission_comments(reddit_submission,
                                              submission.subreddit,
                                              submission.id,
                                              timestamp=last_comment.timestamp)
Exemplo n.º 55
0
def item(id):
    item = Commodity.query.get_or_404(id)
    form = CommentForm()
    if item.clitime == None:
        item.clitime = 0
    item.clitime = item.clitime + 1
    if form.validate_on_submit():
        username = form.reciver.data
        reciver = User.query.filter_by(username=username).first()
        comment = Comment(body=form.body.data,
                          commodity=item,
                          author=current_user._get_current_object(),
                          reciver=reciver)
        print reciver.unreadcomments
        reciver.unreadcomments = reciver.unreadcomments + 1
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('item', id=item.id))
    comments = item.comments.filter_by(disabled=0).order_by(
        Comment.timestamp.asc())
    return render_template('detail.html',
                           item=item,
                           comments=comments,
                           form=form)
Exemplo n.º 56
0
def comment(id_):
    if request.method != 'POST':
        raise RequestMethodNotAllowed(
            msg="The method %s is not allowed for the requested URL" %
            request.method)
    video = db.session.query(Video).filter_by(id=id_).first()
    user_id = g.user.uid
    if video:
        form = VideoPutCommentForm()
        if form.validate_for_api() and form.validate():
            video.comments = video.comments + 1
            db.session.commit()
            comment_content = form.comment.data
            comment_new = Comment(content=comment_content,
                                  uid=user_id,
                                  target=id_)
            db.session.add(comment_new)
            db.session.commit()
            data = {'id': comment_new.id}
            return success(message="评论成功", data=data)
        else:
            return params_error(message=form.get_error())
    else:
        return params_error(message="未查到视频")
Exemplo n.º 57
0
def add_comment(requested_post, comment):
    if requested_post:
        post_id = requested_post.id
        if current_user.is_authenticated:
            new_comment = Comment(author=current_user,
                                  parent_post=requested_post,
                                  comment=comment,
                                  date=generate_date())
            new_notification = Notification(
                user=requested_post.author,
                by_user=current_user.email,
                user_name=current_user.name,
                parent_comment=new_comment,
                category='comment',
                body=f"{current_user.name} commented on your post.",
                date=generate_date())
            db.session.add(new_comment, new_notification)
            db.session.commit()
            return redirect(url_for('post.show_post', post_id=post_id))
        else:
            flash("User is not logged in.")
            return redirect(url_for('post.show_post', post_id=post_id))
    else:
        return abort(404)
def get_all_comments():
    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            id,
            post_id,
            author_id,
            content
        FROM Comments
        """)

        dataset = db_cursor.fetchall()

        comments = []

        for row in dataset:
            comment = Comment(row['id'], row['post_id'], row['author_id'],
                              row['content'])
            comments.append(comment.__dict__)

    return json.dumps(comments)
Exemplo n.º 59
0
def module002_new_comment():
    form = CommentForm()
    id = request.args.get('id')
    errors = None
    if request.method == 'POST':
        post = Post.query.get(id)
        follows = db.session.query(Forum).join(Course, User.courses)\
            .filter(and_(Forum.course_id == post.forum_id)).first()
        if follows is None:
            errors = 'You are not following the course'
        if current_user.is_authenticated and form.validate_on_submit() and follows is not None:
            comment = Comment(author_id=current_user.id,
                              post_id=id,
                              body=form.body.data)
            db.session.add(comment)
            db.session.commit()
            flash("Successfully created a new comment")
        else:
            if errors:
                flash(errors)
            else:
                flash("An error has occurred while sending your comment")
                flash("Post id:" + id + " " + form.body.data)
    return redirect(url_for('module002.module002_post_comments', id=id))
Exemplo n.º 60
0
def get_blog(id):
    blog = yield from Blog.find(id)
    comments = yield from Comment.findAll('blog_id=?', [id],
                                          orderBy='created_at desc')
    for c in comments:
        c.html_content = text2html(c.content)
    blog.html_content = markdown2.markdown(blog.content)
    num = yield from Finance.findNumber('count(id)')
    page = Page(num)
    if num == 0:
        finances = []
    else:
        finances = yield from Finance.findAll(orderBy='created_at desc')
    rev = []
    for fin in finances:
        rev.append(int(fin.revenue))
    return {
        '__template__': 'blog.html',
        'blog': blog,
        'comments': comments,
        'page': page,
        'finances': finances,
        'rev': rev
    }