示例#1
0
def add_comment(request):
    if request.method == 'POST':
        try:
            payload = json.loads(request.body)
            comment_id = uuid.uuid4().hex[:10]
            post_id = payload['post_id']
            body = payload['body']
            posted_by = payload['posted_by']
            parent_id = payload['parent_id']
            posted_date = int(time.time())

            post = get_object_or_404(Post, post_id=post_id)
            post.last_posted_by = posted_by
            post.last_posted_date = posted_date
            post.replies = F('replies') + 1
            post.save()

            comment = Comment(comment_id, post_id, body, posted_by,
                              posted_date, parent_id)
            comment.save()

            response = json.dumps([{
                'success': 'Comment added successfully!',
                'commentid': comment_id
            }])
        except:
            response = json.dumps([{'error': 'Comment  could not be added!'}])
        return HttpResponse(response, content_type='text/json')
    else:
        response = json.dumps([{'error': 'Comment could not be added!'}])
        return HttpResponse(response, status='404', content_type='text/json')
示例#2
0
def comment(txt_id):
    txt = Article.query.get_or_404(txt_id)
    if request.method == 'POST':
        com_name = request.form['nick']
        com_txt = request.form['com_txt']
        if not com_name or not com_txt:
            flash('請輸入暱稱或內容...')
            return redirect(url_for('comment'))
        if len(com_txt) > 100:
            flash('內容請勿超過100個字元...')
            return redirect(url_for('comment'))
        nickname = Nickname.query.filter_by(name=com_name).first()
        if not nickname:
            flash('暱稱不存在...')
            return redirect(url_for('commit'))
        else:
            com_txt = Comment(com_txt=com_txt)
            nickname.n_comment.append(com_txt)
            txt.a_comment.append(com_txt)
            db.session.add(nickname)
            db.session.add(txt)
        db.session.commit()
        flash('回覆成功...')
        return redirect(url_for('comment', txt_id=txt_id))
    com_addtxt = txt.a_comment
    return render_template('comment.html',
                           com_txts=com_addtxt,
                           current_time=datetime.utcnow())
示例#3
0
def comment(request):
    errors = {}
    valid, data = validate_session(request)
    if not valid:
        return data
    if request.method == 'POST':
        try:
            body = json.loads(request.body)
            comment_id = 'c_' + str(uuid.uuid4())
            dweet_id = body['dweet_id']
            comment_data = body['comment']
            created_time = str(datetime.datetime.now())
            account_id = data
            comment = Comment(comment_id=comment_id,
                              dweet_id=dweet_id,
                              comment_data=comment_data,
                              created_time=created_time,
                              account_id=account_id)
            comment.save()
            return getResonse({"status": "success"}, 201)
        except KeyError as ke:
            print ke
            return getResonse({
                "status": "failed",
                "data_missing": ke.message
            }, 422)
        except Exception as e:
            print e
            return getResonse({"status": "failed"}, 500)
    else:
        return getResonse({"status": "failed"}, 405)
示例#4
0
def comment(request):
    if request.method == 'POST':
        r_userid = request.META.get("HTTP_USERID")
        r_parentid = request.POST.get("parentId", '')
        r_content = request.POST.get("content", '')
        r_type = request.POST.get("type", 1)
        if len(r_content) == 0:
            return JsonResponse(common.build_result(CLIENT_ERROR, "内容为空"),
                                safe=False)
        q_blog = MicroBlog.objects.filter(blogId=r_parentid)
        if r_type == 1 and len(q_blog) == 0:
            return JsonResponse(common.build_result(CLIENT_ERROR, "博客不存在"),
                                safe=False)
        q_user = User.objects.filter(userId=r_userid)[0]
        Comment(authorId=r_userid,
                authorName=q_user.nickname,
                authorAvatar=q_user.avatar,
                parentId=r_parentid,
                content=r_content,
                type=r_type).save()
        q_blog[0].commentCount = q_blog[0].commentCount + 1
        q_blog[0].save()
        return JsonResponse(common.build_result(SUCCESS, "success"))
    return JsonResponse(common.build_result(CLIENT_ERROR, ERROR_REQ_METHOD),
                        safe=False)
示例#5
0
def send_comment(post_id, comment_user, comment_text, comment_image):
    usr = User.objects.get(id=comment_user)
    ps = Post.objects.get(id=post_id)

    import uuid
    nameFile = str(uuid.uuid4())[:12]
    imgstr = re.search(r'base64,(.*)', comment_image).group(1)
    # path = default_storage.save('%s.png' % nameFile, ContentFile(imgstr))
    img_file = open("media/%s.png" % nameFile, 'wb')
    img_file.write(base64.b64decode(imgstr))
    img_file.close()

    post = Comment()
    post.comment_text = comment_text
    post.comment_image = nameFile
    post.post_id = ps
    post.comment_user = usr
    post.save()

    user_post = str(usr.username)

    r = redis.StrictRedis()

    if user_post:
        r.publish(
            "".join(['post_', post_id, '_comments']),
            json.dumps({
                "user_post": user_post,
                "title": comment_text,
            }))
示例#6
0
def detail(request, pk):
    d = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post=d)
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CommentForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            comment = form.cleaned_data['comment']
            # print(comment,pk)
            #save comment in Comment model that is in data base
            c = Comment(post=d, comment=comment, user=request.user)
            c.save()
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            context = {'post': d, 'form': form, 'comments': comments}
            return render(request, 'detail.html', context)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CommentForm()
    context = {'post': d, 'form': form, 'comments': comments}
    return render(request, 'detail.html', context)
示例#7
0
def detail(request, pk):
    p = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post_id=pk)
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CommentForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            comment = form.cleaned_data['comment']
            c = Comment(post_id=pk, comment=comment, user=request.user)
            c.save()
            # redirect to a new URL:
            return HttpResponseRedirect(
                reverse('myapp:detail', kwargs={'pk': pk}))

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CommentForm()

    return render(request, 'detail.html', {
        'form': form,
        'p': p,
        'comments': comments
    })
示例#8
0
def play(id,page):
    movie=Movie.query.filter_by(id=id).first()
    if movie:
        movie.playnum=int(movie.playnum)+1
        Movie.add_comment_or_play(movie)
        form=AddComment()
        if form.validate_on_submit():
            if not session['user_id']:
                return redirect(url_for('home.login'))
            data=form.data
            if data['content']:
                comment=Comment(
                    user_id=session['user_id'],
                    movie_id=id,
                    addtime=datetime.datetime.now(),
                    content=data['content']
                )
                if Comment.addcomment(comment):
                    flash("添加评论成功!",'ok')
                    movie.commentnum=int(movie.commentnum)+1
                    Movie.add_comment_or_play(movie)
                    return redirect(url_for('home.play',id=id,page=page))
        shoucang=AddMoviecol()
        if shoucang.validate_on_submit():
            if not Moviecol.query.filter_by(user_id=session['user_id'],movie_id=id).count():
                if Moviecol.moviecol_add(session['user_id'],id):
                    flash("收藏成功!",'ok')
                    return redirect(url_for('home.play',id=id,page=page))
            else:
                if Moviecol.moviecol_del_by_user(session['user_id'],id):
                    flash("取消收藏!",'err')
                    return redirect(url_for('home.play',id=id,page=page))
        pre_page_date=20     #每页20条数据
        comment_count=Comment.query.filter_by(movie_id=id).count() #评论总数
        page_data=Movie.query.filter_by(id=id).first_or_404()
        tag=Tag.query.filter_by(id=page_data.tag_id).first_or_404()
        tag_name=tag.name
        if page is None:
            page=1
        next_page=page+1
        pre_page=page-1
        data=Comment.comment_query(id=id,per_page=page,page_count=pre_page_date)
        if int(comment_count/pre_page_date)==0:
            last_page=int(comment_count/pre_page_date)
        else:
            last_page=int(comment_count/pre_page_date)+1
        comment=[]
        for v in data:
            comment.append({
                'id':v[0],
                'user_name':v[1],
                'movie_title':v[2],
                'content':v[3],
                'addtime':v[4],
                'face':v[5]
            })
    return render_template('home/play.html',shoucang=shoucang,id=id,form=form,page_data=page_data,tag_name=tag_name,comment=comment,last_page=last_page,page=page,next_page=next_page,pre_page=pre_page,comment_count=comment_count)
示例#9
0
def main():
    from myapp.models import Subject
    from myapp.models import User
    from myapp.models import Comment
    i = 0
    all = []
    for line in f:
        i += 1
        data = ''
        try:
            data = json.loads(line)
        except:
            error.write(line + '\n')
            line = line.replace('\\', '\\\\').replace('\r', ' ').replace('\n', ' ').replace('\t', ' ')
            data = json.loads(line)
            error.write('----' + line + '\n')
            error.flush()
        user_name = data['user_name']
        sid = data['sid']
        user = ''
        subject = ''
        try:
            user = User.objects.get(user_name=user_name)
            subject = Subject.objects.get(id=sid)
        except:
            error.write('not exists ------ ' + line + '\n')
            error.flush()
            continue
        key = user_name + '|' + str(sid)
        if key in duplicate:
            error.write('duplicate ------' + line + '\n')
            error.flush()
            continue
        else:
            duplicate[key] = 1
        time = data['time']
        time = time.split(' ')[0].split('-')
        dt2 = datetime.datetime(int(time[0]), int(time[1]), int(time[2]))
        timeid = (dt2 - dt1).days
        timeid = (timeid + 6) / 7 * 7
        all.append(Comment(
            user=user,
            subject=subject,
            star=data['star'],
            time=data['time'],
            timeid=timeid,
            content=data['comment']
        ))
        if i % 20000 == 0:
            print i
            Comment.objects.bulk_create(all)
            all = []

    Comment.objects.bulk_create(all)
    f.close()
    error.close()
示例#10
0
def add_comment(index):
    content = request.form.get('comment_content')
    comment = Comment(content=content)
    comment.user_id = g.user.id
    comment.article_id = index
    # comment.reply_type = 1
    db.session.add(comment)
    db.session.commit()
    flash('Submit comments successfully.')
    return redirect(url_for('detail', index=index))
示例#11
0
def postComment(request):
    if request.method == 'POST':
        comments = request.POST.get("comment")
        user = request.user
        postSno = request.POST.get("postSno")
        post = Post.objects.get(sno=postSno)
        comments = Comment(comments=comments, user=user, post=post)
        comments.save()
        messages.success(request, "Your comment has been posted")

    return redirect(f"/blog/{post.slug}")
示例#12
0
def add_comment(request, id):
    token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
    payload = jwt_decode_handler(token)
    user_id = payload['user_id']
    try:
        user = User.objects.get(pk=user_id)
        post = Post.objects.get(pk=id)
        comment = Comment(user=user, post=post, text=request.data['text'])
        comment.save()
        return Response('Success', status=status.HTTP_201_CREATED)
    except Exception:
        return Response('Error', status.HTTP_401_UNAUTHORIZED)
示例#13
0
def reply(index,user_name):
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(content=form.content.data)
        comment.user_id = g.user.id
        comment.article_id = index  #
        # comment.reply_type = 2
        comment.to_user = user_name
        db.session.add(comment)
        db.session.commit()
        flash('Submit reply successfully.')
        return redirect(url_for('detail', index=index))
    return render_template('reply.html', title='Reply', form=form)
示例#14
0
def commenter(content, post_id):
    post = Post.query.get_or_404(post_id)
    author = post.author
    comment = Comment(content=content, author=current_user, post_id=post_id)
    db.session.add(comment)
    db.session.commit()
    post.nbrcomments += 1
    if not current_user == author:
        #notif=Notif.query.filter_by(title='PostCommented').first()
        #author.notifs.append(notif)
        # author.getnot+=1
        db.session.commit()
    flash('Your comment has been added', 'success')
    return redirect(url_for('posts.post', post_id=post.id))
示例#15
0
    def post(self):
        """ Actions to post, edit, and update comments on the post. """

        user_name = self.user.name
        # Post a comment
        if self.request.get('comment'):
            comment = self.request.get('comment')  # comment content
            author = user_name
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment = Comment(author=author, comment=comment, parent=post.key)
            comment.put()
            self.redirect('/post?post_id=' + post_id)
        # Delete an existing comment
        elif self.request.get('delete'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('delete'))
            comment_to_delete = Comment.get_by_id(comment_id, parent=post.key)
            comment_to_delete.key.delete()
            self.redirect('/post?post_id=' + post_id)
        # Edit an existing comment
        elif self.request.get('edit'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('edit'))
            comment_to_edit = Comment.get_by_id(comment_id, parent=post.key)
            if self.user.name == comment_to_edit.author:  # Verify user is author
                self.render('editcomment.html',
                            comment=comment_to_edit,
                            user_name=user_name,
                            comment_id=comment_id,
                            post_id=post_id)
                return
            else:
                self.redirect('/post?post_id=' +
                              post_id)  # Wish I could flash error msg

        elif self.request.get('update'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('update'))
            comment_to_update = Comment.get_by_id(comment_id, parent=post.key)
            updated_comment_contents = self.request.get('updated-comment')
            updated_comment_contents = cgi.escape(updated_comment_contents)
            comment_to_update.comment = updated_comment_contents
            comment_to_update.put()
            self.redirect('/post?post_id=' + post_id)
        else:
            self.redirect('/')
示例#16
0
def add_comment_reply(userid):
    course_id = request.get_json()['course_id']
    content = request.get_json()['content']
    to_user_id = request.get_json()['to']

    comment_new = Comment(course_id=course_id,
                          content=content,
                          from_user_id=userid,
                          from_user_type=2,
                          to_user_id=to_user_id,
                          to_user_type=1)

    db.session.add(comment_new)
    db.session.commit()

    return Resp.success()
示例#17
0
def post_comment(post_id):
    """
    本文表示、個別ページ post_idから対応するPOSTのデータをDBからとって表示
    本文したにコメント表示
    """
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(author=current_user,
                          post_on=datetime.now(),
                          body=form.body.data,
                          post_id=post_id)
        db.session.add(comment)
        db.session.commit()
        print("comment post success")
        return redirect('/{:d}'.format(post_id))
    return render_template('editor.html', form=form)
示例#18
0
def make_comment(current_user):
    if current_user is not None:
        if request.method == 'POST':
            parsejson = request.get_json()
            commentlist = {}
            newcomment = {"comment_body": parsejson['body']}
            postid = request.args['id']
            userid = current_user.id
            user = User.query.get(userid)
            username = user.username
            post = Post.query.filter_by(id=postid)
            comment = Comment(comment_body=newcomment['comment_body'],
                              usercomment=user,
                              postcomments=post)
            db.session.add(comment)
            db.session.commit()
    return jsonify(commentlist)
示例#19
0
def add_stock_comment(request):
    """This function adds comments to Comments table for a specific stock .

	**Template:**

	:template:'myapp/templates/signle_stock.html'
	"""
    if request.method == 'POST':

        if request.POST.get('name') and request.POST.get('content'):
            comment = Comment()
            comment.author = request.POST.get('name')
            comment.text = request.POST.get('content')
            comment.stock_id = request.POST.get('stock_symbol')
            symbol = request.POST.get('stock_symbol')
            comment.save()

            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
示例#20
0
def add_comment(userid):
    course_id = request.get_json()['course_id']
    content = request.get_json()['content']
    course = Course.query.get(course_id)

    comment_new = Comment(
        course_id=course_id,
        content=content,
        from_user_id=userid,
        from_user_type=1,
        to_user_id=course.admin_id,
        to_user_type=2
    )

    db.session.add(comment_new)
    db.session.commit()

    return Resp.success()
示例#21
0
文件: views.py 项目: Kimboloe/ohsiha
def main_page(request, country_code="global"):

    file = open('spotify_countries.json')
    countries = json.load(file)
    comments = Comment.objects.all().order_by("date")

    if country_code == None:
        country_code = "global"

    top_ten = get_top_ten(country_code)

    login_form = AuthenticationForm(request.POST)

    if request.method == 'GET' and request.is_ajax():

        data = dict(request.GET)
        first = next(iter(data.keys()))
        print(first)

        if first == 'Song':
            song = data['Song'][0]
            artist = data['Artist'][0]
            #call get_lyrics scraper
            lyrics = get_lyrics(song, artist)
            return HttpResponse(lyrics, content_type="text")

    if request.method == 'POST' and request.is_ajax():
        json_response = json.loads(request.body)
        if json_response["messageType"] == "comment":
            comment = json_response["comment"]
            user = json_response["user"]
            new_comment = Comment(user=user, comment=comment)
            new_comment.save()
            response = "< " + user + " >: " + comment
            return HttpResponse(response)

    return render(
        request, 'base.html', {
            'login_form': login_form,
            'top_tracks': top_ten,
            'countries': countries,
            'comments': comments
        })
示例#22
0
def comment_edit(request, song_id, comment_id=None):
    """コメントの編集"""
    song = get_object_or_404(Song, pk=song_id)  # 親の曲を読む
    # comment_idが指定されている(修正時)
    if comment_id:
        comment = get_object_or_404(Comment, pk=comment_id)
    # comment_idが指定されていない(追加時)
    else:
        comment = Comment()

    if request.method == 'POST':
        # POSTされたrequestデータからフォームを作成
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.song = song
            comment.save()
            return redirect('myapp:comment_list', song_id=song_id)
    else:  # GETの時
        form = CommentForm(instance=comment)

    return render(request, 'myapp/comment_edit.html',
                  dict(form=form, song_id=song_id, comment_id=comment_id))
示例#23
0
def play(id,page=None):
    movie = Movie.query.get(id)
    if page ==  None:
        page = 1
    comments = Comment.query.filter(and_(Comment.movie_id==movie.id,Comment.user_id==User.id)).order_by(Comment.addtime.desc()).paginate(page,limits)
    form = CommentForm()
    if form.validate_on_submit():
        data = form.data
        comment = Comment(
            content= data['content'],
            movie_id = movie.id,
            user_id = session['user_id']
        )
        movie.commentnum += 1                       # 评论数量 + 1
        db.session.add(movie)
        db.session.add(comment)
        db.session.commit()
        flash('提交评论成功!','ok')
        return redirect(url_for('project.play',id=movie.id,page=1))
    movie.playnum += 1                              # 播放数量 + 1
    db.session.add(movie)
    db.session.commit()
    moviecol = Moviecol.query.filter(Moviecol.user_id==session['user_id'],Moviecol.movie_id==id).first()
    return render_template('home/play.html',movie=movie,form=form,comments=comments,moviecol=moviecol)
示例#24
0
def add_comment(request):
    post_id = request.POST['post']
    post = Post.objects.get(id = post_id)
    c = Comment(text = request.POST['text'])
    post.comment_set.add(c)
    return redirect('post', post_id)
示例#25
0
def commentview(request,id):
    x=request.POST['comment']
    s=Comment(message=x,MessageId_id=id)
    s.save()
    return HttpResponseRedirect('/myapp/article/%s'% id)
示例#26
0
    def handle(self, *args, **options):
        # now do the things that you want with your models here
        password = "******"
        exp_posts = 50
        exp_users = 20
        avg_votes_per_post = 5
        avg_comments_per_post = 3

        # Post.objects.all().delete()

        rootExists = User.objects.filter(username="******").count()
        if (rootExists < 1):
            self.stdout.write("Creating root user")
            User.objects.create_superuser("root", "*****@*****.**", password)

        num_posts = Post.objects.all().count()
        num_users = User.objects.all().count()
        num_votes = Vote.objects.all().count()
        num_comments = Comment.objects.all().count()

        faker = Faker()

        self.stdout.write("Default password: "******"Number of posts: " + str(num_posts))
        self.stdout.write("Number of votes: " + str(num_votes))
        self.stdout.write("Number of comments: " + str(num_comments))
        self.stdout.write("Number of users: " + str(num_users))

        if (num_users < exp_users):
            self.stdout.write("Creating " + str(exp_users - num_users) +
                              " Users")
            for x in range(num_users + 1, exp_users + 1):
                username = faker.name().replace(" ", ".")
                email = username + "@test.com"
                User.objects.create_superuser(username, email, password)
                self.stdout.write("   " + username)
            num_users = User.objects.all().count()

        if (num_posts < exp_posts):
            self.stdout.write("Creating " + str(exp_posts - num_posts) +
                              " Posts")
            for x in range(num_posts + 1, exp_posts + 1):
                day_offset = randint(1, 364)
                pub_date = timezone.now() - datetime.timedelta(days=day_offset)
                u = self.randomUser()
                title = faker.text()
                self.stdout.write("   [" + u.username + "] " + title)
                rec = Post()
                rec.author = u
                rec.title = title
                rec.text = faker.text()
                rec.created_date = pub_date
                rec.published_date = pub_date
                rec.save()
            num_posts = Post.objects.all().count()

        self.stdout.write("Voting...")
        while (num_votes < avg_votes_per_post * num_posts):
            user = self.randomUser()
            post = self.randomPost()
            voted = Vote.objects.all().filter(post=post, author=user).count()
            if (post.author != user and voted == 0):
                rec = Vote()
                rec.author = user
                rec.post = post
                rec.created_date = self.randomDate(post.created_date,
                                                   timezone.now())
                rec.save()
                num_votes = Vote.objects.all().count()
                self.stdout.write(
                    str(num_votes) + ": " + user.username + " voted for [" +
                    post.title + "]")

        self.stdout.write("Commenting...")
        while (num_comments < avg_comments_per_post * num_posts):
            user = self.randomUser()
            post = self.randomPost()
            rec = Comment()
            rec.author = user
            rec.post = post
            rec.contents = faker.text()
            rec.created_date = self.randomDate(post.created_date,
                                               timezone.now())
            rec.save()
            num_comments = Comment.objects.all().count()
            self.stdout.write(
                str(num_comments) + ": " + user.username + " commented on [" +
                post.title + "]")