Example #1
0
def add_comment(uid,tid,text,parent=None):
    try:
        id = generateId()
        creator = LcUser.objects.get(pk = int(uid))
        thread = Thread.objects.get(pk = int(tid))
        if (parent != None):
            parent = Comment.objects.get(pk = int(parent))
        timestamp = int(time())
        c = Comment(id = id, creator=creator, thread = thread, parent = parent, text=text, time_created = timestamp)
        c.save()
        notified = [creator.id]
        if (parent != None):
            if parent.creator.id != creator.id:
                u.notify(parent.creator.id,c.id,True)
                notified.append(parent.creator.id)

        followers = u.get_followers(int(tid))
        
        for f in followers:
            if f not in notified:
                u.notify(f,c.id,False)
    
        p = -1
        if parent:
            p = parent.id
        
        return (True,id)
    except:
        connection._rollback()
        return (False,str(traceback.format_exc()))
    def setUp(self):
        db.app = test_app
        db.create_all()
        user = User()
        user.username = self.username
        user.set_password(self.password)
        db.session.add(user)

        comment = Comment()
        comment.name = self.comment_name
        comment.text = self.comment_text

        tag = Tag()
        tag.title = self.tag_title

        post = Post()
        post.title = self.post_title
        post.text = self.post_text
        post.publish_date = self.post_publish_date

        # add relationships to other tables
        post.user = user
        post.tags = [tag]
        post.comments = [comment]

        db.session.add(user)
        db.session.add(comment)
        db.session.add(tag)
        db.session.add(post)
        db.session.commit()
Example #3
0
def post(post_id, page=1):
    form = CommentForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            comment = Comment()
            comment.name = form.name.data
            comment.text = form.text.data
            comment.post_id = post_id
            comment.date = datetime.datetime.now()

            db.session.add(comment)
            db.session.commit()
            return redirect(url_for('post', post_id=post.id))

    post = Post.query.get_or_404(post_id)
    tags = post.tags

    comments = post.comments.order_by(Comment.date.desc()
        ).paginate(page, 10)
    recent, top_tags = sidebar_data()

    return render_template(
        'post.html',
        post=post,
        tags=tags,
        comments=comments,
        recent=recent,
        top_tags=top_tags,
        form=form
    )
Example #4
0
def post(post_id):
    form = CommentForm()

    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.datetime.now()

        db.session.add(new_comment)
        db.session.commit()

    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template(
        'post.html',
        post=post,
        tags=tags,
        comments=comments,
        recent=recent,
        top_tags=top_tags,
        form=form
    )
Example #5
0
def insert_data():
    # 不需要在这里创建库,应该使用数据库升级命令`db upgrade`来创建库
    # db.create_all()

    # 注意调用顺序
    Role.generate_fake()
    User.generate_fake()
    Tag.generate_fake()
    Post.generate_fake()
    Comment.generate_fake(1000)
Example #6
0
def get_post(post_id):
    form = CommentForm()
    post = Post.query.get_or_404(post_id)
    if g.current_user and form.validate_on_submit():
        comment = Comment(form.text.data)
        comment.post_id = post_id
        comment.user_id = g.current_user.id
        comment.date = datetime.datetime.now()
        db.session.add(comment)
        db.session.commit()
        form.text.data = ""

    return render_template('post.html', post=post, form=form)
Example #7
0
 def create(self, request, *args, **kwargs):
     print(request.data)
     data = request.data
     comment = Comment(author=User.objects.get(username=data['author']),
                       photo=Photo.objects.get(pk=data['photo']),
                       text=data['text'])
     comment.save()
     return Response(
         {
             'text': comment.text,
             'author': comment.author.username,
             'date_create': comment.date_create,
             'id': comment.id
         },
         status=status.HTTP_200_OK)
Example #8
0
def article(post_id):
    post = Post.query.filter_by(id=post_id).first()
    form = CommentForm()
    if form.validate_on_submit():
        newcomment = Comment()
        newcomment.name = current_user.name
        newcomment.text = form.content.data
        newcomment.post_id = post.id
        newcomment.user_id = current_user.id
        newcomment.date = datetime.now()
        db.session.add(newcomment)
        db.session.commit()
        return redirect(url_for('.article', post_id=post.id))

    comments = Comment.query.filter_by(post_id=post_id).order_by(
        Comment.date).all()

    if post is None:
        return redirect(url_for('.listarticle'))
    else:
        title = post.title
        text = post.text
        publish_date = post.publish_date
        user_id = post.user_id
        user = User.query.filter_by(id=user_id).first()

        return render_template('post.html',
                               form=form,
                               comments=comments,
                               text=text,
                               username=user.username,
                               publish_date=publish_date,
                               siteheading=title,
                               backgroundpic='/static/img/post2_bg.jpg',
                               post=post)
Example #9
0
def post_comment(request):
    form = CommentForm(request.POST)
    if form.is_valid():
        if form.cleaned_data['answer_to']:
            answer_to = form.cleaned_data['answer_to']
            content_id = None
        else:
            answer_to = None
            content_id = form.cleaned_data['content_id']

        if request.user.is_authenticated:
            new_comment = Comment(author_user=request.user,
                                  passed=True,
                                  text=form.cleaned_data['text'],
                                  answer_to_id=answer_to,
                                  content_id=content_id)
        else:
            new_comment = Comment(author_name=form.cleaned_data['author_name'],
                                  text=form.cleaned_data['text'],
                                  answer_to_id=answer_to,
                                  content_id=content_id)
        if Settings.objects.get(id=1).comments_manual_valuation == 0:
            new_comment.passed = 1
        new_comment.save()

        return HttpResponse(content=serializers.serialize(
            'json', [Comment.objects.get(id=new_comment.id)],
            use_natural_foreign_keys=True,
            use_natural_primary_keys=True),
                            status=201,
                            content_type='application/json')
    else:
        return HttpResponse(status=400)
Example #10
0
def post(post_id):
    form = CommentForm()
    post = Post.objects(id=post_id).get_or_404()
    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.date = datetime.datetime.now()
        post.comments.append(new_comment)
        post.save()
    tags = post.tags
    comments = post.comments

    return with_sidebar_render('post.html',
                               post=post,
                               tags=tags,
                               comments=comments,
                               form=form)
Example #11
0
def page(task_id):
    task = Task.query.get_or_404(task_id)
    if not task.task_auth():
        abort(403)
    comment_form = CommentForm()
    comments = Comment.query.filter_by(task_id=task.id).order_by(
        Comment.date).all()
    if comment_form.validate_on_submit():
        new_comment = Comment()
        new_comment.text = comment_form.text.data
        new_comment.task_id = task.id
        new_comment.user_id = current_user.id
        db.session.add(new_comment)
        db.session.commit()
        return redirect(url_for('task.page', task_id=task.id))
    return render_template(
        'task/task_page.html',
        task=task,
        comments=comments,
        comment_form=comment_form,
    )
Example #12
0
def post(post_id):
    form = CommentForm()
    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.datetime.now()
        db.session.add(new_comment)
        db.session.commit()
        form.name.data = None
        form.text.data = None
    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    if request.method == 'POST':
        return redirect(url_for('blog.post', post_id=post_id))
    else:
        return render_template('blog/post.html',
                               post=post,
                               tags=tags,
                               comments=comments,
                               recent=recent,
                               top_tags=top_tags,
                               form=form)
Example #13
0
def post(post_id):
    form = CommentForm()

    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.datetime.now()

        db.session.add(new_comment)
        db.session.commit()

    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template('post.html',
                           post=post,
                           tags=tags,
                           comments=comments,
                           recent=recent,
                           top_tags=top_tags,
                           form=form)
Example #14
0
def post(post_id):
    form = CommentForm()
    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.now()
        db.session.add(new_comment)
        db.session.commit()
        return redirect(url_for('.post', post_id=post_id))
    post = Post.query.get_or_404(post_id)
    # 添加阅读量
    post.read = post.read + 1
    db.session.add(post)
    db.session.commit()

    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    # 是否有编辑权限
    permission = Permission(UserNeed(post.user.id))
    is_edit = permission.can() or admin_permission.can()
    if g.is_login:
        form.name.data = current_user.username
    return render_template('post.html',
                           post=post,
                           tags=tags,
                           is_edit=is_edit,
                           comments=comments,
                           form=form)
Example #15
0
def add_comment():
    form = CommentForm()
    if form.validate_on_submit():
        if Stump.query.filter(Stump.id == form.stump_id.data).first():
            comment = Comment(text=form.comment_text.data,
                              stump_id=form.stump_id.data,
                              user_id=current_user.id)
            db.session.add(comment)
            db.session.commit()
            flash('Comment has been added')
    else:
        for field, errors in form.errors.items():
            for error in errors:
                flash('Error in field "{}": - {}'.format(
                    getattr(form, field).label.text, error))
    return redirect(request.referrer)
Example #16
0
def comment(request, experience_id):
    if request.method == 'POST':
        u = request.user
        profile = u.profile.get()
        form = AddComment(request.POST)
        if form.is_valid():
            text = form.cleaned_data['text']
            c = Comment(
                text=text,
                create_date=datetime.datetime.now(),
                user_own=u,
            )
            e = Experience.objects.get(id=experience_id)
            e.comments.append(c)
            e.save()
    return HttpResponseRedirect(reverse('experience', args=(experience_id, )))
Example #17
0
def show_post(post_id):
    post = Post.query.get(post_id)
    if request.method == 'GET':
        comments = Comment.query.filter_by(post_id=post_id).all()
        return render_template('/articles/article.html',
                               post=post,
                               comments=comments)
    else:
        comment_text = request.form['text']
        comment_creation_date = datetime.datetime.utcnow()
        comment = Comment(post_id=post_id,
                          user_name=current_user.user_name,
                          text=comment_text,
                          comment_creation_date=comment_creation_date)
        try:
            db.session.add(comment)
            db.session.commit()
        except:
            return 'Error'
    comments = Comment.query.filter_by(post_id=post_id).all()
    return render_template('/articles/article.html',
                           post=post,
                           comments=comments)
Example #18
0
def commentarticle(post_id):
    form = CommentForm()
    post = Post.query.filter_by(id=post_id).first()
    if form.validate_on_submit():
        newcomment = Comment()
        newcomment.name = current_user.name
        newcomment.text = form.content.data
        newcomment.post_id = post.id
        newcomment.user_id = current_user.id
        newcomment.date = datetime.now()
        db.session.add(newcomment)
        db.session.commit()
        return redirect(url_for('.commentarticle', post_id=post.id))

    comments = Comment.query.filter_by(post_id=post_id).order_by(
        Comment.date).all()
    time = datetime.now()

    return render_template('post/commentarticle.html',
                           time=time,
                           form=form,
                           post=post,
                           comments=comments,
                           backgroundpic='/static/img/post-bg.jpg')
Example #19
0
    def post(self, blog_id=None):
        if not blog_id:
            abort(404)
        blog = Blog.query.get(blog_id)
        if not blog:
            abort(404)
        args = comment_post_parser.parse_args()
        reply_to = args['replyTo']
        content = args['content']
        author = args['author']
        href = args['href']

        pattern = re.compile('@(.*?)\s')
        if reply_to:
            # 被回复的 comment
            c = Comment.query.filter_by(id=int(reply_to)).first()
            if not c:
                abort(404)
            receiver = c.author
            comment = Comment(author, receiver, content)
            comment.time = time.time() * 1000
            comment.blog_id = blog_id
            comment.save()
            total_comments = len(blog.comments.all())
            u = User.query.filter_by(username=receiver).first()
            if u:
                message = Message(author, content)
                message.href = '/post/{}?pageIdx={}#comment{}'.format(blog_id,
                                                                      str((total_comments + 15 - 1) / 15),
                                                                      str(comment.id))
                message.time = time.time() * 1000
                message.users = u
                message.checked = '0'
                message.message_type = '有人回复你'
                message.save()
                emit_new_message_to_current_user(u, Message)
            # 根据正则表达式来匹配 content 中的用户名,再做出提醒
            if (pattern.search(content)):
                username_array = pattern.findall(content)
                for a in username_array:
                    u = User.query.filter_by(username=a).first()
                    if u:
                        message = Message(author, content)
                        message.href = '/post/{}?pageIdx={}#comment{}'.format(blog_id,
                                                                              str((total_comments + 15 - 1) / 15),
                                                                              str(comment.id))
                        message.time = time.time() * 1000
                        message.users = u
                        message.checked = '0'
                        message.message_type = '有人@你'
                        message.save()
                        emit_new_message_to_current_user(u, Message)
            return comment
        comment = Comment(author, '', content)
        comment.time = time.time() * 1000
        comment.blog_id = blog_id
        comment.save()
        total_comments = len(blog.comments.all())
        if (pattern.search(content)):
            username_array = pattern.findall(content)
            for a in username_array:
                u = User.query.filter_by(username=a).first()
                if u:
                    message = Message(author, content)
                    message.href = '/post/{}?pageIdx={}#comment{}'.format(blog_id,
                                                                          str((total_comments + 15 - 1) / 15),
                                                                          str(comment.id))
                    message.time = time.time() * 1000
                    message.users = u
                    message.checked = '0'
                    message.message_type = '有人@你'
                    message.save()
                    emit_new_message_to_current_user(u, Message)
        return comment
Example #20
0
def insert_data():
    with app.app_context():
        # 不需要在这里创建库,应该使用数据库升级命令`db upgrade`来创建库
        # db.create_all()

        # 这里设定了3种角色
        role_admin = Role(name='admin')
        role_admin.description = "administrator role"
        role_poster = Role(name='poster')
        role_poster.description = "the registered user role"
        role_default = Role(name='default')
        role_default.description = 'the unregistered user role'
        db.session.add(role_admin)
        db.session.add(role_poster)
        db.session.add(role_default)

        # add User
        admin = User(username='******')
        admin.email = '*****@*****.**'
        admin.password = '******'
        admin.confirmed = True
        admin.roles.append(role_admin)
        admin.roles.append(role_poster)
        admin.roles.append(role_default)
        db.session.add(admin)

        user01 = User(username='******')
        user01.email = '*****@*****.**'
        user01.password = '******'
        user01.confirmed = True
        user01.roles.append(role_poster)
        user01.roles.append(role_default)
        db.session.add(user01)

        user02 = User(username='******')
        user02.email = '*****@*****.**'
        user02.password = '******'
        user02.confirmed = True
        user02.roles.append(role_poster)
        user02.roles.append(role_default)
        db.session.add(user02)

        # add Tag and Post
        tag_one = Tag('Python')
        tag_two = Tag('Flask')
        tag_three = Tag('SQLAlechemy')
        tag_four = Tag('Jinja')
        tag_list = [tag_one, tag_two, tag_three, tag_four]

        s = "Example Text"

        for i in xrange(1, 101):
            new_post = Post("Post {}".format(i))
            if i % 2:
                new_post.user = user01
            else:
                new_post.user = user02
            new_post.publish_date = datetime.datetime.utcnow()
            new_post.text = s
            new_post.tags = random.sample(tag_list, random.randint(1, 3))
            db.session.add(new_post)

        # add comment
        comment01 = Comment()
        comment01.name = 'comment01'
        comment01.text = 'comment text'
        comment01.post_id = 99
        comment01.date = datetime.datetime.utcnow()
        db.session.add(comment01)

        comment02 = Comment()
        comment02.name = 'comment02'
        comment02.text = 'comment text'
        comment02.post_id = 100
        comment02.date = datetime.datetime.utcnow()
        db.session.add(comment02)

        db.session.commit()
Example #21
0
    def post(self, post_id=None,comment_id=None):
        print "In commentPostAPI"
        print "post_id is %s" %post_id
        print "comment_id is %s" %comment_id
        if comment_id or not post_id:
            abort(400)
        else:
            args = comment_post_parser.parse_args(strict=True)
            user = User.verify_auth_token(args['token'])
            post = Post.query.filter_by(id=post_id).first()
            print "user is %s,post is %s" %(user,post)
            if not user or not post:
                abort(401)
            if user.username == 'admin123':
                new_comment = Comment()
                new_comment.user = args['name']
                new_comment.date = datetime.datetime.now()
                new_comment.text = args['text']
                new_comment.post_id = post_id
            else:
                comment_user = args['name']

                if user.username != comment_user:
                    abort(401)
                new_comment = Comment()
                new_comment.name = user.username
                new_comment.date = datetime.datetime.now()
                new_comment.text = args['text']
                new_comment.post_id = post_id

            db.session.add(new_comment)
            db.session.commit()
            return new_comment.id, 201
Example #22
0
def insert_comment(userid, username, content, article_id):
    com = Comment(userid, username, content, article_id)
    db_session.add(com)
    db_session.commit()
Example #23
0
def add_comment(subject, user, comment, submit_date):
    com = Comment(subject=subject,
                  user=user,
                  comment=comment,
                  submit_date=submit_date)
    com.save()
Example #24
0
def add_comment(subject, user, comment, submit_date):
    com = Comment(subject=subject, user=user, comment=comment, submit_date=submit_date)
    com.save()
Example #25
0
File: dengo.py Project: paganre/lc
def arxiv_threads(tids,r):
    """
        Put threads with ids [tids] to archive
        Tags and comments of the thread are also stored
    """
    deleted_comments = []
    deleted_threads = []
    try:
        headers = db.get_thread_headers(tids)
        for h in headers:
            if (int(time()) - int(h['time']))>DENGO_TIME_LIMIT:
                creator = LcUser.objects.get(pk = h['cid'])
                try:
                    Thread.objects.get(id=h['id'])
                except Thread.DoesNotExist:
                    #
                    # Save the thread
                    #
                    t = Thread(id=h['id'],
                               creator=creator,
                               title=h['title'],
                               summary=h['summary'],
                               suggested_title=h['suggested_title'],
                               url = h['url'],
                               domain = h['domain'],
                               time_created = h['time'])
                    t.save()
                    #
                    # Save tags
                    #
                    for redistag in h['tags']:
                        tagid = redistag[0]
                        tagname = redistag[1]
                        tag = Tag.objects.filter(name = tagname)
                        if len(tag) == 0:
                            tag = Tag(id = tagid, name = tagname)
                            tag.threads.add(t)
                            tag.save()
                        else:
                            tag = tag[0]
                            if len(tag.threads.filter(id = t.id)) == 0:
                                tag.threads.add(t)
                                tag.save()
                    #
                    # Save comments
                    #
                    cids = db.get_thread_comments(h['id'])
                    comments = db.get_comments(cids)
                    for comment in comments:
                        if comment['pid'] != -1:
                            try:
                                parent = Comment.objects.get(pk = comment['pid'])
                            except:
                                connection._rollback()
                                parent = None
                        else:
                            parent = None
                        c = Comment(id = comment['cid'],
                                    creator=creator,
                                    thread = t,
                                    parent = parent,
                                    text=comment['text'],
                                    time_created = comment['time'],
                                    up = comment['up'],
                                    down = comment['down'])
                        c.save()
                    #
                    # Remove thread data from redis
                    # Later: Put into a function
                    #
                    # Remove thread header
                    r.delete('t:'+str(h['id']))
                    # Remove thread from active thread id list
                    r.lrem('act:ids',h['id'])
                    # Remove thread ids from t:tags:<tid>
                    tagids = r.lrange('t:tags:'+str(h['id']),0,-1)
                    r.delete('t:tags:'+str(h['id']))
                    for tagid in tagids:
                        r.zrem('tag:t:'+str(tagid),h['id'])
                    # Remove comments associated with tid
                    cids = r.lrange('t:comm:'+str(h['id']),0,-1)
                    deleted_comments = deleted_comments + cids
                    r.delete('t:comm:'+str(h['id']))
                    for cid in cids:
                        r.delete('c:'+str(cid))
                        r.delete('c:up:'+str(cid))
                        r.delete('c:down:'+str(cid))
                    # Remove follower data
                    foll_uids = r.smembers('t:foll:'+str(h['id']))
                    for uid in foll_uids:
                        r.srem('u:foll:'+str(uid),str(h['id']))
                    r.delete('t:foll:'+str(h['id']))
                    deleted_threads = deleted_threads + [h['id']]
                else:
                    #
                    # Remove thread data from redis
                    # Later: Put into a function
                    #
                    # Remove thread header
                    r.delete('t:'+str(h['id']))
                    # Remove thread from active thread id list
                    r.lrem('act:ids',h['id'])
                    # Remove thread ids from t:tags:<tid>
                    tagids = r.lrange('t:tags:'+str(h['id']),0,-1)
                    r.delete('t:tags:'+str(h['id']))
                    for tagid in tagids:
                        r.zrem('tag:t:'+str(tagid),h['id'])
                    # Remove comments associated with tid
                    cids = r.lrange('t:comm:'+str(h['id']),0,-1)
                    deleted_comments = deleted_comments + cids
                    r.delete('t:comm:'+str(h['id']))
                    for cid in cids:
                        r.delete('c:'+str(cid))
                        r.delete('c:up:'+str(cid))
                        r.delete('c:down:'+str(cid))
                    # Remove follower data
                    foll_uids = r.smembers('t:foll:'+str(h['id']))
                    for uid in foll_uids:
                        r.srem('u:foll:'+str(uid),str(h['id']))
                    r.delete('t:foll:'+str(h['id']))
                    deleted_threads = deleted_threads + [h['id']]
            else:
                print "Thread is new"
        # Delete the sorted act:id list since if act:id has been updated
        if not deleted_threads:
            r.delete('act:ids:sorted')
        # Update user keys - remove archived comments from u:up u:down u:comm
        for comment_id in deleted_comments:
            u_up_keys = r.keys('u:up:*')
            for key in u_up_keys:
                r.srem(key,str(comment_id))
            u_down_keys = r.keys('u:down:*')
            for key in u_down_keys:
                r.srem(key,str(comment_id))
            u_comm_keys = r.keys('u:comm:*')
            for key in u_comm_keys:
                r.lrem(key,comment_id)
        # Update user keys - remove archived threads from u:notif
        u_notif_keys = r.keys('u:notif:*')
        for key in u_notif_keys:
            for i,notif in enumerate(r.zrange(key,0,-1)):
                notif_data = msgpack.unpackb(notif)
                if notif_data['tid'] in deleted_threads:
                    # NOTE: works only for redis 2.0+
                    r.zremrangebyrank(key,i,i)
        # Remove empty tag keys
        tag_threads = r.keys('tag:t:*')
        for t in tag_threads:
            if len(r.zrange(t,0,-1))==0:
                tagid = int(t.split(':')[2])
                tagname = r.get('tag:'+str(tagid))
                r.delete('tag:'+str(tagid))
                r.delete('tag:'+str(tagname))
        return (True,deleted_threads) # threads are in archive
    except:
        connection._rollback()
        return (False,str(traceback.format_exc()))
Example #26
0
    def test_comments(self):
        # add two users
        r = Role.query.filter_by(name='poster').first()
        self.assertIsNotNone(r)
        u1 = User('john')
        u1.email = '*****@*****.**'
        u1.password = '******'
        u1.confirmed = True
        u1.roles.append(r)
        u2 = User('susan')
        u2.email = '*****@*****.**'
        u2.password = '******'
        u2.confirmed = True
        u2.roles.append(r)
        db.session.add_all([u1, u2])
        db.session.commit()

        # add a post
        post = Post(title='title of the post')
        post.text = 'body of the post'
        post.user = u1
        db.session.add(post)
        db.session.commit()

        # write a comment
        response = self.client.post(url_for('api.new_post_comment',
                                            id=post.id),
                                    headers=self.get_api_headers(
                                        'susan', 'dog'),
                                    data=json.dumps({
                                        'name':
                                        'comment name',
                                        'text':
                                        'Good [post](http://example.com)!'
                                    }))
        self.assertTrue(response.status_code == 201)
        json_response = json.loads(response.data.decode('utf-8'))
        url = response.headers.get('Location')
        self.assertIsNotNone(url)
        self.assertTrue(json_response['name'] == 'comment name')
        self.assertTrue(
            json_response['text'] == 'Good [post](http://example.com)!')

        # get the new comment
        response = self.client.get(url,
                                   headers=self.get_api_headers('john', 'cat'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertTrue(json_response['url'] == url)
        self.assertTrue(json_response['name'] == 'comment name')
        self.assertTrue(
            json_response['text'] == 'Good [post](http://example.com)!')

        # add another comment
        comment = Comment(name='another comment name')
        comment.text = 'Thank you!'
        comment.user = u1
        comment.post = post
        db.session.add(comment)
        db.session.commit()

        # get the two comments from the post
        response = self.client.get(url_for('api.get_post_comments',
                                           id=post.id),
                                   headers=self.get_api_headers(
                                       'susan', 'dog'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('comments'))
        self.assertTrue(json_response.get('count', 0) == 2)

        # get all the comments
        response = self.client.get(url_for('api.get_comments', id=post.id),
                                   headers=self.get_api_headers(
                                       'susan', 'dog'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('comments'))
        self.assertTrue(json_response.get('count', 0) == 2)
Example #27
0
def setup():
    db.create_all()

    admin_role = Role("admin")
    admin_role.description = "admin"
    db.session.add(admin_role)

    default_role = Role("default")
    default_role.description = "default"
    db.session.add(default_role)

    guest_role = Role("guest")
    guest_role.description = "guest"
    db.session.add(guest_role)

    db.session.commit()

    admin = User("Admin")
    admin.nickname = "管理员"
    admin.email = "*****@*****.**"
    admin.set_password('admin')
    admin.roles.append(admin_role)
    db.session.add(admin)

    official = User("PublicOfficial")
    official.nickname = "公共库用户"
    official.email = "*****@*****.**"
    official.set_password('official')
    admin.roles.append(admin_role)
    db.session.add(official)

    db.session.commit()

    # 创建原始公共库目录(共5个)
    script1 = Script('always_work.sg')
    script1.content = """Strategy T1:
    return 1"""
    script1.description = "永远合作"
    script1.user = official
    script1.is_private = False
    db.session.add(script1)

    script2 = Script('random_example.sg')
    script2.content = "Strategy T2:i = RANDOM(1);if(i==0){return 0}else{return 1}"
    script2.description = "`听天由命`,背叛与合作的几率为 50% (RANDOM 为系统范围内真随机)"
    script2.user = official
    script2.is_private = False
    db.session.add(script2)

    script3 = Script('slow_work.sg')
    script3.content = "Strategy T3:if(COUNT == 1){return 1}else{return CUR}"
    script3.description = "`慢半拍`:开局合作,随后一直跟随对方上一轮的选择"
    script3.user = official
    script3.is_private = False
    db.session.add(script3)

    script4 = Script('elusive_work.sg')
    script4.content = "Strategy T4:if (COUNT == 1){return 1}else {i = RANDOM(9);if (i == 9){return 0}else{return CUR}}"
    script4.description = "改进版`慢半拍`,开局合作,随后随机自我背叛,大几率跟随对方上一轮的选择"
    script4.user = official
    script4.is_private = False
    db.session.add(script4)

    script5 = Script('never_forgive.sg')
    script5.content = "Strategy T5:if(FLAG){return 0}else{return 1}"
    script5.description = "永不原谅,只要对方存在过背叛行为,就一直背叛"
    script5.user = official
    script5.is_private = False
    db.session.add(script5)

    db.session.commit()

    # 创建文章评论
    comment1 = Comment('comment1')
    comment1.user = admin
    comment2 = Comment('comment2')
    comment2.user = official
    comment3 = Comment('comment3')
    comment3.user = admin
    db.session.add(comment1)
    db.session.add(comment2)
    db.session.add(comment3)
    db.session.commit()

    post1 = Post('Post1', 'Content1')
    post1.user = official
    post1.category = PostCategory.General
    post1.comments.append(comment1)
    post1.comments.append(comment2)

    post2 = Post('Post2', 'Content2')
    post2.user = admin
    post2.category = PostCategory.Feedback
    post2.comments.append(comment3)

    db.session.add(post1)
    db.session.add(post2)

    db.session.commit()