示例#1
0
def trade_detail(goodId):
    post = Post.query.get_or_404(goodId)
    form = CommentForm()
    if form.validate_on_submit():
        if current_user.is_anonymous:
            flash(u'请登录后再尝试评论帖子')
            return redirect(url_for('auth.passport'))
        else:
            comment = Comment(body=form.body.data, post=post,
            author = current_user._get_current_object())
            db.session.add(comment)
            db.session.commit()
            flash(u'你的评论已提交.')
            return redirect(url_for('.trade_detail', goodId=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) // \
            current_app.config['JXNUGO_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['JXNUGO_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    author = current_user._get_current_object()
    return render_template('trade/trade_detail.html', post=post, form=form,
                           comments=comments, pagination=pagination,user=author)
示例#2
0
文件: views.py 项目: heymars/flaskq
def comment(id):
    form = CommentForm()
    type = request.args.get('type')
    if type:
        answer = Answer.query.get_or_404(id)
        comments = answer.comments.order_by(Comment.timestamp.asc()).all()
        if form.validate_on_submit():
            comment = Comment(body=form.body.data,
                              answer=answer,
                              author=current_user._get_current_object())
            db.session.add(comment)
            db.session.commit()
            comments = answer.comments.order_by(Comment.timestamp.asc()).all()
            return render_template('_comments.html', form=form, comments=comments)
    else:
        question = Question.query.get_or_404(id)
        comments = question.comments.order_by(Comment.timestamp.asc()).all()
        if form.validate_on_submit():
            comment = Comment(body=form.body.data,
                              question=question,
                              author=current_user._get_current_object())
            db.session.add(comment)
            db.session.commit()
            comments = question.comments.order_by(Comment.timestamp.asc()).all()
            return render_template('_comments.html', form=form, comments=comments)
    return render_template('_comments.html', form=form, comments=comments)
def apply(group_id):
    group = Group.query.get_or_404(group_id)

    applicants = []

    for application in group.applications:
        if not application.is_passed:
            applicants.append(application.applicant)

    if current_user in group.users:
        flash('您已经是组内成员,请勿重复申请加入!')
    elif current_user in applicants:
        flash('您已提交申请,请勿重复提交,请耐心等待回复!')
    else:
        application = Application(applicant=current_user._get_current_object(),
                                  group=group)
        apply = current_user.username + '申请加入'
        comment = Comment(body=apply,
                          group=group,
                          author=current_user._get_current_object())
        db.session.add(comment)
        db.session.commit()
        db.session.add(application)
        flash('申请已提交!')
    return redirect(url_for('main.carpool', id=group_id))
示例#4
0
def question(id):
    """show the questions"""
    answerForm = AnswerForm()
    commentForm = CommentForm()
    question = Question.query.filter_by(id=id).first_or_404()
    answer_id =  request.args.get('answer_id', -1, type=int)
    comments = Comment.query.filter_by(answer_id=answer_id).order_by(Comment.timestamp.desc())
    answer= Answer.query.filter_by(id=answer_id)
    if current_user.can(Permission.WRITE_ARTICLES) and \
       answerForm.validate_on_submit():
                answer = Answer(answer=answerForm.body.data,
                                 author=current_user._get_current_object(),
                                 authorname=current_user.username,
                                 question=question )
                db.session.add(answer)
                return redirect(url_for('.question', id=id))

    if current_user.can(Permission.WRITE_ARTICLES) and \
       commentForm.validate_on_submit():
                comment = Comment(comment=commentForm.body.data,
                                 author=current_user._get_current_object(),
                                 authorname=current_user.username,
                                 answer=answer)
                db.session.add(answer)
                return redirect(url_for('.question', id=id))

    answers = Answer.query.filter_by(question_id=question.id).order_by(Answer.timestamp.desc())            
    asker = User.query.filter_by(id=question.author_id).first()
    return render_template("question.html", question=question, asker=asker,
                           answerForm=answerForm, answers=answers, comments=comments,
                           commentForm=commentForm, answer_id=answer_id)
示例#5
0
文件: views.py 项目: py-py/changer
def report():
    today = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)

    transaction_today = Transaction.query. \
        filter(Transaction.date_trans > today). \
        filter(Transaction.user == current_user._get_current_object()).all()

    start_cash_state = Deals.query. \
        filter(Deals.user == current_user._get_current_object()). \
        filter(Deals.date_operation < today). \
        order_by(Deals.id.desc()).first()

    finish_cash_state = Deals.query. \
        filter(Deals.cash == current_user.cash). \
        order_by(Deals.id.desc()).first()

    # if not start_cash_state:
    #    start_cash_state = finish_cash_state

    my_cash = current_user.cash
    currency_state_cash = get_dict(transaction_today)[my_cash]

    return render_template('report.html',
                           today=today,
                           d=ziping(transaction_today),
                           d_state=currency_state_cash,
                           start_cash_state=start_cash_state,
                           finish_cash_state=finish_cash_state)
示例#6
0
def start_discussion(text, title=None, schools=None, form=None):
	""" Starts a discussion with some comment text """
	if not schools:
		schools = [g.school,]
	if title:
		d = Discussion(
			title=title,
			schools=schools,
			creator=current_user._get_current_object())
	elif form:
		d = Discussion(
			schools=schools,
			creator=current_user._get_current_object())
		if form:
			form.populate_obj(d)
	else:
		return None
	import datetime
	d.created = datetime.datetime.now()
	d.last_comment_time = datetime.datetime.now()
	d.save()
	c = Comment(
		text = text,
		creator = current_user._get_current_object(),
		discussion = d)
	c.created = d.created
	c.save()
	return d
示例#7
0
def question(id):
    question = Question.query.get_or_404(id)
    form = ReplyForm()
    if form.validate_on_submit():
        if question.replys.filter_by(author=current_user._get_current_object()).first():
            flash(u'已经回答过这个问题了')
            return redirect(url_for('.question', id=question.id, page=-1))
        else:
            reply = Reply(body=form.body.data,
                          question=question,
                          author=current_user._get_current_object())
            db.session.add(reply)
            flash(u'回答成功')
            return redirect(url_for('.question', id=question.id, page=-1))
    session['redirect_like'] = ''
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (question.replys.count() - 1) // \
            current_app.config['FLASKY_REPLYS_PER_PAGE'] + 1
    pagination = question.replys.order_by(Reply.timestamp.asc()).paginate(
        page, per_page=current_app.config['FLASKY_REPLYS_PER_PAGE'],
        error_out=False)
    replys = pagination.items
    return render_template('question.html', questions=[question], form=form,
                           replys=replys, pagination=pagination)
示例#8
0
文件: views.py 项目: aztec8/ds
def read_article(slug):
    article = Article.query.filter_by(slug=slug).first_or_404()
    # get the latest article
    # we have to account for article.ids that have been deleted
    # we have gaps between some ids
    index = 1
    next_article = Article.query.filter_by(id=article.id + index).first()
    while next_article is None:
        index = index + 1
        next_article = Article.query.filter_by(id=article.id + index).first()
        if next_article is not None:
            break
        else:
            next_article = Article.query.filter_by(id=article.id - index).first()

    # get related articles
    article_category = Category.query.filter_by(id=article.category_id).first()
    related_articles = article_category.posts.order_by(Article.post_date.desc()).limit(3)

    # comment shit
    comment_form = CommentForm(prefix='comment')
    if comment_form.validate_on_submit() and comment_form.submit.data:
        if current_user.can(Permission.COMMENT):
            comment = Comment(
                body=comment_form.body.data,
                author=current_user._get_current_object(),
                article=article
                )
            db.session.add(comment)
            flash('Your comment has been posted!')
            return redirect(url_for('articles.read_article', slug=article.slug))
        # elif comment_form.email.data:
        #     flash('an email was entered')
        else:
            flash('please login to comment')

    comments = article.comments.filter_by(reply_to=None).order_by(Comment.timestamp.desc()).limit(20)

    reply_form = ReplyForm(prefix='reply')
    if reply_form.validate_on_submit() and reply_form.submit.data:
        if current_user.can(Permission.COMMENT):
            og_comment = Comment.query.filter_by(id=reply_form.comment_id.data).first()
            reply = Comment(
                body=reply_form.body.data,
                author=current_user._get_current_object(),
                article=article,
                reply_to=og_comment
                )
            db.session.add(reply)
            flash('hey you posted a reply!')
            return redirect(url_for('articles.read_article', slug=article.slug))
        else:
            flash('you must login in order to reply')
    return render_template('articles/view.html', article=article,
        next_article=next_article, related_articles=related_articles,
        comment_form=comment_form, comments=comments,
        reply_form=reply_form)
示例#9
0
def post_new():
    form = PostForm()
    if form.validate_on_submit():
        #category is an object(<app.models.Category object at 0x10faded90>)
        post = Post(title=form.title.data,category=Category.query.get(form.category.data),body=form.body.data,
                    author=current_user._get_current_object())
        res = Like(post=post, user=current_user._get_current_object(), liked=False)
        db.session.add(post,res)
        db.session.commit()
        flash('Your post has been published.')
        return redirect(url_for('main.post',id=post.id))
    return render_template('post_new.html',form=form)
示例#10
0
def index():
    # print(type(current_user._get_current_object()))
    # if()
    user_rep = str(current_user._get_current_object())
    form = form_choice(user_rep, limit_exceed, False)
    if current_user.can(Permission.WRITE_POST):
        if form.validate_on_submit():
            # print(current_user._get_current_object())
            post = Post(body=form.body.data,
                        author=current_user._get_current_object())
            db.session.add(post)
            form = form_choice(user_rep, limit_exceed, True)
            return redirect(url_for(".index"))
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('index.html', form=form, posts=posts)
示例#11
0
def default_address():
    user = current_user._get_current_object()
    address_id = request.args.get('id', -1, type=int)
    if address_id!=-1 and Address.query.get(address_id) in user.addresses:
        user.address_default_id = address_id

    return redirect(url_for('mall.address'))
示例#12
0
def post(id):
    """Поддержка комментариев в странице отдельных сообщений"""
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(
            body=form.body.data,
            post=post,
            author=current_user._get_current_object()
        )
        db.session.add(comment)
        flash(u'Your comment has been published.')
        # page=-1 чтобы последний введенный комментарий сразу отображался на странице
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    # FLASKY_COMMENTS_PER_PAGE - размер одной страницы с комментариями
    if page == -1:
        # page = (post.comments.count() - 1) // current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
        page = (post.comments.count() - 1) // 21
    # pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
    #     page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'], error_out=False
    # )
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
            page, per_page=20, error_out=False
        )
    comments = pagination.items
    return render_template(
        'post.html', posts=[post], form=form, comments=comments, pagination=pagination
    )
示例#13
0
def new():
    form = PostForm()
    if not current_user.can(Permission.WRITE_ARTICLES):
        abort(403)
    if form.validate_on_submit():
        post = Post(body=form.body.data,
                    title=form.title.data,
                    viewed_count=0,
                    author=current_user._get_current_object(),
                    tags_txt=form.tags.data)
        db.session.add(post)
        tags = form.tags.data.split(';')
        for tag in tags:
            ttag = Tag.query.filter_by(content=tag).first()
            if ttag is not None:
                ttag.refer_count = ttag.refer_count + 1
            else:
                ttag = Tag(content=tag, refer_count=1)
            post_tag = PostTag(post=post, tag=ttag)
            db.session.add(ttag)
            db.session.add(post_tag)
        flash(messages.post_create_ok)
        db.session.commit()
        return redirect(url_for('main.index', shows='home'))
    if None == form.body.data:
        form.body.data = '# 标题\n\n内容'
    if None == form.title.data:
        form.title.data = '输入博文名字'
    if None == form.tags.data:
        form.tags.data = '标签通过;隔开。'
    return render_template('edit.html', form=form)
示例#14
0
def my_messages():
    delete_message_form = DeleteMessageForm(prefix='delete_message')
    if delete_message_form.validate_on_submit():
        m = Message.query.get(int(delete_message_form.message_id.data))
        if m:
            db.session.delete(m)
    all_read_message_form = AllReadMessageForm(prefix='all_read_message')
    if all_read_message_form.validate_on_submit():
        ms = Message.query.all()
        for m in ms:
            if not m.read:
                m.read = True
    message_form = MessageForm(prefix='message')
    if message_form.validate_on_submit():
        for m_id in request.form.getlist('message-checkbox'):
            if message_form.read.data:
                mess = Message.query.get(int(m_id))
                mess.read = True
            elif message_form.check_delete.data:
                msg = Message.query.get(int(m_id))
                db.session.delete(msg)

    message_form.checkbox.data = False
    message_form.check_delete.data = False
    message_form.read.data = False
    page = request.args.get('page', 1, type=int)
    messages = Message.query.filter_by(receiver=current_user._get_current_object()).order_by(Message.timestamp.desc()).paginate(page, error_out=False)

    return render_template('auth/messages/my-messages.html', messages=messages, deleteMessageForm=delete_message_form,
                           allReadMessageForm=all_read_message_form, messageForm=message_form)
示例#15
0
def url_for_school(endpoint, school=None, user_school=False, **values):
    """ Similar to typical url for, except this will rewrite the base to the specified school """
    url = url_for(endpoint, **values)
    csn = g.school.name  # current school name
    fsn = school.name if hasattr(school,
                                 'name') else school  # future school name
    if fsn is None and user_school:
        u = current_user._get_current_object()
        c = get_school_context(u)
        if c:
            fsn = c.name
    # The name of the default school never appears in the path: it is always the base url
    if school == g.default_school:
        fsn = None
    # Requesting the default/ global school
    if fsn is None:
        if g.is_default_school:
            return url
        else:
            return url.replace('/' + csn, '', 1)
    # Requesting a particular school
    else:
        if csn == fsn:
            return url
        elif g.is_default_school:
            return url.replace('/', '/' + fsn + '/', 1)
        else:
            return url.replace('/' + csn, '/' + fsn, 1)
示例#16
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
      form.validate_on_submit():
        post = Post(body=form.body.data,
                    author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    #requset.args为请求的查询字符串
    #get()中有三个参数,key, default, type
    #如果没有指定page,默认为1,type = init为了确保若参数无法转换为整数,返回默认值
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page,
        per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)
    #Post.timestamp.desc()为按时间戳降序排列
    #paginate()方法接受三个参数,起始页,每一页的数目,错误标志,True为404,False为空列表
    posts = pagination.items
    #迭代器,index.html中要用到
    return render_template('index.html',
                           form=form,
                           posts=posts,
                           show_followed=show_followed,
                           pagination=pagination)
示例#17
0
def write():
    form = PostForm()
    drop_form = DropForm()
    if form.validate_on_submit():
        post = Post( name = form.name.data,
                     body_md = form.body_md.data,
                     page = form.page.data )
        if not post.page:
            post.excerpt = form.excerpt.data
            post.author = current_user._get_current_object()
            # tags
            set_tags(post, form._tag_list)
            # categories
            set_categories(post, form.categories.old.data, form.categories._list)
            #
        if form._main_image is not None:
            post.main_image = form._main_image
        #
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('main.post', slug=post.slug))
    old_photos = Image.query.all()
    return render_template('write_post.html',
                           form=form,
                           drop_form=drop_form,
                           old_photos=old_photos)
示例#18
0
def toggle(type, id):
    if current_user.is_anonymous():
        return jsonify({'anon': True})
    """ Toggles current user's interest in a proposal """
    from app.mod_proposal import Proposal
    from app.mod_event import Event

    u = current_user._get_current_object()
    remove = request.form.get('action', 'add') == 'remove'
    attribute = request.form.get('attribute', None) or None
    if type == 'event':
        cls = Event
    else:
        cls = Proposal
    # Now try and load the document
    obj = cls.objects.get_or_404(id=id)
    # Do the adding or removing
    if remove:
        remove_user_interest(u, obj, cls, only=attribute)
    else:
        add_user_interest(u, obj, cls, extra=attribute)

# Used for updating the list of interested users
    interested_users = []
    for user in obj.interested_users:
        interested_users.append(user.display_name)

    return jsonify({
        'num_interested': obj.num_interested,
        'next': 'remove' if obj.user_is_interested(u) else 'add',
        'interested_users': interested_users
    })
示例#19
0
文件: views.py 项目: peter14f/flasky
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data, 
                          author=current_user._get_current_object(),
                          post=post)
        db.session.add(comment)
        flash('Your comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / \
                current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(
                    Comment.timestamp.desc()).paginate(
                        page=page, 
                        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
                        error_out=False)
    comments = pagination.items
    return render_template('post.html', 
                           posts=[post], 
                           form=form, 
                           comments=comments,
                           pagination=pagination)
示例#20
0
def create_store():
    form = PostForm()
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    page = request.args.get("page", 1, type=int)
    pagination = Post.query.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config["JOKENIA_POSTS_PER_PAGE"], error_out=False
    )
    posts = pagination.items
    if form.validate_on_submit():

        file = request.files["uploadPhotoes"]

        filename = None
        if file and file.filename.split(".")[-1] in ["jpeg", "png", "jpg"]:
            filename = secure_filename(file.filename)
            file.save(os.path.join(current_app.config["UPLOAD_FOLDER"], filename))

        post = Post(
            product=form.product.data,
            short_description=form.short_description.data,
            Long_description=form.Long_description.data,
            uploadPhotoes=filename,
            price=form.price.data,
            author=current_user._get_current_object(),
        )
        db.session.add(post)
        db.session.commit()
        flash("There are errors in your form")
        return redirect(url_for("main.index"))
    else:
        flash("Product has been added")
    return render_template("main/create_store.html", form=form, posts=posts, pagination=pagination)
示例#21
0
def post(id):
    post = Post.query.get_or_404(id)
    if request.method == 'GET':
        post.click_num += 1
        db.session.add(post)
        db.session.commit()
    upload = Upload.query.get(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        db.session.commit()
        flash(u'你的评论已经被发表。')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / \
               current_app.config['COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           upload=upload,
                           comments=comments,
                           pagination=pagination)
示例#22
0
文件: views.py 项目: Julzmbugua/A21
def tasks_per_category(id):
    cat = Category.query.order_by(Category.id.desc()).all()
    form = AddTask()
    # form.C_name.choices = [(category.id, category.name) for category in Category.query.all()]

    category_id = Task.category_id
    username = current_user.username
    user = User.query.filter_by(username=username).first()

    # tasks_per_category = Task.query.filter_by(category_id=category_id).all()
    if form.validate_on_submit():
        task = Task(name=form.name.data,
                    due_date=form.due_date.data,
                    user=current_user._get_current_object(),
                    category_id=id)

        db.session.add(task)

        return redirect(url_for('main.task'))

    tasks = user.tasks.filter_by(category_id=id).all()

    return render_template('tasks_per_category.html',
                           form=form,
                           tasks=tasks,
                           user=user,
                           cat=cat)
示例#23
0
文件: views.py 项目: stepsame/flaskq
def index():
    form = QuestionForm()
    if current_user.can(Permission.ASK) and form.validate_on_submit():
        question = Question(body=form.body.data, detail=form.detail.data, author=current_user._get_current_object())
        db.session.add(question)
        db.session.flush()
        question_activity = Activity(
            verb="asked", object=question, actor_id=current_user.id, timestamp=question.timestamp
        )
        db.session.add(question_activity)
        return redirect(url_for(".index"))
    page = request.args.get("page", 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get("show_followed", ""))
    if show_followed:
        query = current_user.followed_activities
    else:
        query = Activity.query
    pagination = query.order_by(Activity.timestamp.desc()).paginate(
        page, per_page=current_app.config["FLASKQ_ACTIVITIES_PER_PAGE"], error_out=False
    )
    activities = pagination.items
    comment_form = CommentForm()
    return render_template(
        "index.html",
        form=form,
        activities=activities,
        show_followed=show_followed,
        pagination=pagination,
        comment_form=comment_form,
    )
示例#24
0
文件: api.py 项目: jbalthis/projecto
def post(project):
  feeditem = FeedItem(data=request.json)
  # This is required as current_user is a werkzeug LocalProxy
  feeditem.author = current_user._get_current_object()
  feeditem.parent = project
  feeditem.save()
  return jsonify(**feeditem.serialize(restricted=("title", "parent", "author"), include_key=True))
示例#25
0
文件: views.py 项目: yaoice/flask
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash(u'评论已发布.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)

    #page值为-1时, 会计算评论的总量和总页数,得出真正要显示的页数
    if page == -1:
        page = (post.comments.count() -
                1) / current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1

    #评论按照时间戳顺序排列,新评论显示在列表的底部.
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination)
示例#26
0
def get_feedback():
    if request.method == 'POST':
        recipients = request.form.getlist('email')
        share = request.form.get('share-objectives')
        share_objectives = share == 'share-objectives'

        for recipient in recipients:
            user = current_user._get_current_object()
            other_user = User.objects.filter(email=recipient).first()

            entry = Entry()
            entry.requested_by = user.email
            entry.requested_from = other_user.email
            entry.requested_by_name = user.full_name
            entry.requested_from_name = other_user.full_name
            entry.template = request.form.get('feedback-template')
            entry.share_objectives = share_objectives
            if share_objectives:
                # get and attach objectives
                pass
            entry.save()

            log_entry = LogEntry()
            log_entry.entry_type = 'feedback'
            log_entry.owner = user
            log_entry.entry = entry
            log_entry.save()
            log_entry.add_tag('Feedback')

            _send_feedback_email(log_entry, user, other_user)
        flash('Submitted request')

    return render_template('feedback/get-feedback.html')
示例#27
0
def post(id):
    post = Post.query.get_or_404(id)

    # Allowing comments
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('Comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / \
            current_app.config['ANTISOCIAL_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['ANTISOCIAL_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items

    # we send a list so that _post.html template can be used
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination)
示例#28
0
文件: views.py 项目: yaoice/flask
def index():
    form = PostForm()
    #检查当前用户是否有写文章的权限
    if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
        post = Post(body=form.body.data, author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    #posts = Post.query.order_by(Post.timestamp.desc()).all()    #按时间戳进行降序排序(大到小排序)
    #return render_template('index.html', form=form, posts=posts)
    
    #分页(默认20条记录 paginate()方法 配置文件FLASKY_POSTS_PER_PAGE = 20 )
    page = request.args.get('page', 1, type=int)
    
    # 显示所有博客文章 或 只显示所关注用户的博客文章 
    show_followed = False  #默认显示所有文章
    #如果cookie的show_followed字段中有值,则显示所关注用户的文章
    if current_user.is_authenticated():
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts #限制只显示所关注用户的文章
    else:
        query = Post.query  #显示所有文章
            
    #pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False)
    pagination = query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False)
    posts = pagination.items
    #return render_template('index.html', form=form, posts=posts, pagination=pagination)
    return render_template('index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination)
示例#29
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(
            body=form.body.data,
            like_count=0,  # todo: isso aqui deveria ser setado como default!
            author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    show_followed = False
    # show only post by followers
    if current_user.is_authenticated():
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page,
        per_page=current_app.config['ANTISOCIAL_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    return render_template('index.html',
                           form=form,
                           posts=posts,
                           show_followed=show_followed,
                           pagination=pagination)
示例#30
0
def index():
    show_followed = False
    form = PostForm()
    page_count = PageCount.query.get_or_404(1)
    if page_count.count is None:
        page_count.count = 1
    else:
        page_count.count = int(page_count.count) + 1
    flash("Site has experienced a breakdown, inconvenience is regretted! ")
    if current_user.can(
            Permission.WRITE_ARTICLE) and form.validate_on_submit():
        post = Post(body=form.body.data,
                    author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('main.index'))
    # posts = Post.query.order_by(Post.timestamp.desc()).all()
    if current_user.is_authenticated():
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page,
        per_page=current_app.config['FLASKY_POST_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    return render_template('index.html',
                           posts=posts,
                           form=form,
                           pagination=pagination,
                           show_followed=show_followed,
                           count=page_count.count)
示例#31
0
def group(id):
    group = Group.query.filter_by(id=id).first()
    if group is None:
        abort(404)

    form = PostForm()
    if form.validate_on_submit():
        if group.has_already_join(current_user):
            post = Post(
                body=form.body.data,
                author=current_user._get_current_object(),
                like_count=0,  # todo: isso aqui deveria ser setado como default!
                group_id=id)
            db.session.add(post)
        else:
            flash("You can't write post.")
        return redirect(url_for('.group', id=id))

    page = request.args.get('page', 1, type=int)
    pagination = Post.query.filter_by(group_id=id).order_by(
        Post.timestamp.desc()).paginate(
            page,
            per_page=current_app.config['ANTISOCIAL_POSTS_PER_PAGE'],
            error_out=False)
    posts = pagination.items

    return render_template('group.html',
                           group=group,
                           posts=posts,
                           pagination=pagination,
                           form=form)
示例#32
0
文件: views.py 项目: v2up/queyue
def index():
    twitter_form = TwitterForm()
    if request.method == 'POST' and twitter_form.validate_on_submit():
        twitter = Twitter(
            content=twitter_form.content.data,
            author=current_user._get_current_object())  #author与model中的User一致
        db.session.add(twitter)
        flash('发布成功', 'alert-success')
        return redirect(url_for('main.index'))
    some_events = Event.query.order_by(Event.new_time.desc()).limit(7)
    some_topics = Topic.query.order_by(Topic.post_time.desc()).limit(7)
    some_members = User.query.order_by(User.reg_date.desc()).limit(7)
    pagination = None
    foled_twitters = None
    if current_user.is_authenticated:
        page = request.args.get('p', 1, type=int)
        pagination = current_user.foled_twitters.order_by(
            Twitter.post_time.desc()).paginate(
                page, per_page=current_app.config['ITEMS_PER_PAGE'])
        foled_twitters = pagination.items
    return render_template('index.html',
                           form=twitter_form,
                           events=some_events,
                           topics=some_topics,
                           members=some_members,
                           twitters=foled_twitters,
                           pagination=pagination)
示例#33
0
文件: pool.py 项目: pooldin/pooldwww
 def wrapper(*args, **kwargs):
     campaign_id = kwargs['id']
     c = campaign.get(campaign_id)
     organizer = campaign.organizer(c)
     if current_user._get_current_object() != organizer:
         return message, 401
     return fn(*args, **kwargs)
示例#34
0
def _add_comment():
    """ajax add comment HTML
    """
    per_page = current_app.config['FLASKY_ANSWERS_PER_PAGE']
    id = request.args.get('answer_id')
    answer = Answer.query.get_or_404(id)
    comment =request.args.get('comment')
    answers = Answer.query.get_or_404(id)
    page = 1
    result= False
    if current_user.can(Permission.COMMENT):
        comment = Comment(body=comment,
                          author=current_user._get_current_object(),
                          answer_id=id)
        db.session.add(comment)
        db.session.commit()
        page = (answer.comments.count()-1)/per_page + 1
        result=True
    pagination = Comment.query.order_by(Comment.timestamp).filter_by(answer_id=id).paginate(
        page,per_page=per_page,error_out=False
    )
    macro_comment = get_template_attribute("_comments.html", "render_comments")
    macro_page = get_template_attribute("_page.html", "render_page")
    comments = pagination.items
    return jsonify({'result': result,
                    'comment_html': macro_comment(comments),
                    'page_html': macro_page(pagination),
                    'comments_timestamp': [comment.timestamp for comment in comments],
                    'comments_id': [comment.id for comment in comments]
                    })
示例#35
0
文件: views.py 项目: Toruitas/tomt
def question(id):
    """
    Shows question description etc, and maybe also creator info.
    Also has answer question form
    Todo: Delete button. Should it be a simple button with a POST and refresh, or should it be a form?
    :param id:
    :return:
    """
    form = CreateAnswerForm()
    question = Question.query.get_or_404(id)  # get gets things based on primary key, otherwise use .filter_by
    if form.validate_on_submit() and current_user.can(Permission.CREATE):
        # Add answer
        answer = Answer(author=current_user._get_current_object(), question=question, content=form.answer.data)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for('main.question', id=id))
    elif form.validate_on_submit() and current_app.has_answered(id=id):
        # just in case
        flash("Sorry, you can't answer a question more than once")
        return redirect(url_for('main.question', id=id))
    elif not question.visible and not current_user.is_administrator():
        # just in case
        flash("That page isn't ready for the public yet, sorry!")
        return redirect(url_for("main.index"))
    else:
        creator = User.query.filter_by(id=question.creator_id).first()
        if question.solved:
            accepted = Answer.query.get_or_404(question.accepted_id)
        else:
            accepted = None
        # some way to find if a user has already answered the question
        return render_template("question.html", creator=creator, id=id, form=form, Permission=Permission,
                               question=question, a=accepted)
示例#36
0
def post(id):
    post = Post.query.get_or_404(id)
    if post.views is None:
        post.views = 1
    else:
        post.views = int(post.views) + 1
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('Your comment have been publish')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / \
            current_app.config['FLASK_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['FLASK_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination,
                           endpoint='.post')
示例#37
0
文件: views.py 项目: hellckt/SONGXUE
def detail(id):
    courses = Course.query.get_or_404(id)
    # print current_user.is_applied_by(courses)
    form = CommentForm(prefix="comment-form")
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          course=courses,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash(u'你的评论已发布。')
        return redirect(url_for('course.detail', id=courses.id, page=-1))
    application_form = ApplicationForm(prefix="application")
    if application_form.validate_on_submit():
        application = Application()
        flash(u'报名成功!')
        return redirect(url_for('course.detail', id=courses.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (courses.comments.count() - 1) / \
               current_app.config['SONGXUE_COMMENTS_PER_PAGE'] + 1
    pagination = courses.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['SONGXUE_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    # courses = [courses] 为course.html中courses[0].id,转化为list,否则会报错
    return render_template('course/course.html', form=form, courses=[courses],
                           comments=comments, pagination=pagination,
                           application_form=application_form)
示例#38
0
def comment(id):

    comment = Comment.query.get_or_404(id)
    authorid = comment.author_id
    postid = comment.post_id

    post = Post.query.get_or_404(postid)
    user = User.query.get_or_404(authorid)
    page = request.args.get('page', 1, type=int)

    form = ReplyForm()

    if form.validate_on_submit():
        user_url = url_for('user', username=user.username, _external=True)
        reply = Comment(body_html= '<a href="' + user_url + '">@' + user.username + '</a> ' + form.body.data,
                          timestamp=datetime.utcnow(),
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(reply)
        db.session.flush()
        r = comment.reply(reply)
        db.session.add(r)
        db.session.commit()

        flash('Your comment has been published.')
    commenturl = url_for('post', id=post.id, page=page, _external=True)
    if user.email:
        reply_notification(user, g.user, commenturl)
    return redirect(url_for('post', id=post.id, page=page))
示例#39
0
def stripe_connect():
    # TODO :: Error responses need to be end user friendly
    usr = current_user._get_current_object()
    if not 'state' in request.args:
        return 'Unauthorized', 401
    csrf_token = request.args['state']
    if not current_app.csrf._get_token() == csrf_token:
        return 'Unauthorized', 401

    if 'code' in request.args:
        code = request.args['code']
        stripe_secret_key = current_app.config.get('STRIPE_SECRET_KEY')
        try:
            user.associate_stripe_authorization_code(usr, code,
                                                     stripe_secret_key)
        except PreviousStripeAssociationError:
            return 'Previous Stripe Connect account association found.', 409
        except ExternalAPIUsageError:
            return 'An internal error prevented your request from being completed.', 500
        except (ExternalAPIError, ExternalAPIUnavailableError):
            return 'An error occoured with an external service preventing your request from being completed.', 500

        sess = session._get_current_object()
        if sess['next']:
            url = sess['next']
            del sess['next']
            return redirect(url)

        return redirect(url_for('account.stripe_connect_success'))
    elif 'error' in request.args:
        # Redirect user to account for the connect denial in our analytics
        return redirect(url_for('account.stripe_connect_denied'))
示例#40
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
        post = Post(body=form.body.data, author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)

    # Выбор между отображением всех сообщений или только пренадлежащих
    # зарегистрированным пользователям. Берется из кук

    # per_page - число элементов на странице
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    # pagination = query.order_by(
    #     Post.timestamp.desc()
    # ).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False)
    pagination = query.order_by(
        Post.timestamp.desc()
    ).paginate(page, per_page=20, error_out=False)
    posts = pagination.items
    return render_template(
        'index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination
    )
def give_feedback():
    user = current_user._get_current_object()
    feedback = user.feedback

    return render_template(
        'feedback/feedback-for-others.html',
        feedback_requests=feedback)
示例#42
0
def post(id):
    '''
		current_user是上下文代理对象
		真正的User对象要使用current_user._get_current_object()获取
	'''
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('Your comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / current_app.config.get(
            'FLASK_COMMENTS_PER_PAGE', 10) + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config.get('FLASK_COMMENTS_PER_PAGE', 10),
        error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination,
                           Permission=Permission)
def write_post():
	form = PostForm()
	if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
		post = Post(title=form.title.data, body=form.body.data,author=current_user._get_current_object())
		db.session.add(post)
		return redirect(url_for('main.index', posts=[post]))
	return render_template('write_post.html', form=form)
示例#44
0
def conference(id):
    """
    显示对应id的会议的详细信息。
    """
    conference = Conference.query.filter_by(id=id).first()
    form = CommentForm()
    if form.validate_on_submit():
        if (form.body.data == ""):
            flash("You can't submit empty comment!")
        else:
            comment = Comment(body=form.body.data, \
                            author=current_user._get_current_object(), \
                            conference=conference)
            db.session.add(comment)
            flash("Your comment have been published!")
            return redirect(
                url_for("main.conference", id=conference.id, page=-1))

    page = request.args.get("page", 1, type=int)

    if (page == -1):
        page = (conference.comments.count()-1) / \
                current_app.config['XING_COMMENTS_PER_PAGE'] + 1
    pagination = conference.comments.order_by(Comment.time_stamp.asc()).paginate(page, \
                 per_page=current_app.config['XING_COMMENTS_PER_PAGE'], \
                 error_out=False)
    comments = pagination.items
    return render_template("conference_context.html",
                           conference=conference,
                           form=form,
                           comments=comments,
                           pagination=pagination)
示例#45
0
文件: views.py 项目: doocan/zuixinke
def publish():
    form = PostForm()

    try:
        category = Category.query.filter_by(tag=form.tag.data).first()
        if category is None:
            category = Category(tag=form.tag.data)
            db.session.add(category)
            db.session.commit()
    # 这个方法并不好,应该自定义个category为None的异常再捕获
    # 不知为什么第一个tag会提交个null上去
    except:
        abort(403)

    if form.validate_on_submit():
        # 不加上下面这句的话,post里的category=category会提示局部变量未定义
        category = Category.query.filter_by(tag=form.tag.data).first()

        post = Post(
            title=form.title.data,
            summary=form.summary.data,
            body=form.body.data,
            category=category,  #这个地方差点要了我的老命,千万别写成category=form.tag.data
            author=current_user._get_current_object())

        db.session.add(post)
        db.session.commit()
        return redirect(url_for('blog.post', id=post.id))
    return render_template('blog/publish.html', form=form)
示例#46
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
      form.validate_on_submit():
        post = Post(body=form.body.data,
                    author=current_user._get_current_object()
                    )  #这里要用真正的用户对象因此调用_get_current_object()方法
        db.session.add(post)
        return redirect(url_for('.index'))
    page = request.args.get(
        'page', 1, type=int)  #这里得到的是一个int型,也就是一个数字,默认1,1代表这个路由渲染第一页,当然也可以改成其他页
    show_followed = False
    if current_user.is_authenticated():
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page,
        per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)  #传入渲染的页数和每页的纪录数
    #可选参数为 error_ out,当其设为 True 时(默认值),如果请求的页数超出了范围,则会返回 404 错误;如果 设为 False,页数超出范围时会返回一个空列表。
    posts = pagination.items
    return render_template('index.html',
                           form=form,
                           posts=posts,
                           show_followed=show_followed,
                           pagination=pagination)
示例#47
0
def index():
    form = QuestionForm()
    if current_user.can(Permission.WRITE_QUESTIONS) and form.validate_on_submit():
        question = Question(body=form.body.data, content=form.content.data,
                            author=current_user._get_current_object())
        db.session.add(question)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    show_followed = 0
    session['act'] = u'提出'
    if current_user.is_authenticated:
        show_followed = int(request.cookies.get('show_followed', '0'))
    if show_followed == 1:
        query = current_user.followed_questions
    elif show_followed == 2:
        query = current_user.followed_replys
        session['act'] = u'回答'
        pagination = query.order_by(Reply.timestamp.desc()).paginate(
            page, per_page=current_app.config['FLASKY_REPLYS_PER_PAGE'],
            error_out=False)
        replys = pagination.items
        return render_template('index.html', form=form, replys=replys,
                               show_followed=show_followed, pagination=pagination, act=session.get('act'))
    else:
        query = Question.query
    pagination = query.order_by(Question.timestamp.desc()).paginate(
        page, per_page=current_app.config['FLASKY_QUESTIONS_PER_PAGE'],
        error_out=False)
    questions = pagination.items
    return render_template('index.html', form=form, questions=questions,
                           show_followed=show_followed, pagination=pagination, act=session.get('act'))
def get_feedback():

    if request.method == 'POST':
        recipients = User.objects.filter(
            email__in=request.form.getlist('q'))
        share = bool(request.form.get('share-objectives'))
        user = current_user._get_current_object()

        if recipients:
            for recipient in recipients:

                feedback = create_log_entry(
                    'feedback',
                    requested_by=user.email,
                    requested_from=recipient.email,
                    requested_by_name=user.full_name,
                    requested_from_name=recipient.full_name,
                    template=request.form.get('feedback-template'),
                    share_objectives=share)

                if share:
                    for objective in user.objectives:
                        feedback.link(objective)

                feedback.add_tag('Feedback')

                _send_feedback_email(feedback, user, recipient)

            flash('Submitted request')

            return redirect(url_for('.requested_feedback'))

        flash('Failed submitting request(s)', 'error')

    return render_template('feedback/get-feedback.html')
示例#49
0
def change_email_request():
    """Respond to existing user's request to change their email."""
    form = ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            new_email = form.email.data
            token = current_user.generate_email_change_token(new_email)
            change_email_link = url_for('account.change_email', token=token,
                                        _external=True)
            get_queue().enqueue(
                send_email,
                recipient=new_email,
                subject='Confirm Your New Email',
                template='account/email/change_email',
                # current_user is a LocalProxy, we want the underlying user
                # object
                user=current_user._get_current_object(),
                change_email_link=change_email_link
            )
            flash('A confirmation link has been sent to {}.'.format(new_email),
                  'warning')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid email or password.', 'form-error')
    return render_template('account/manage.html', form=form)
示例#50
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
            form.validate_on_submit():
        post = Post(body=form.body.data,
                    author=current_user._get_current_object())
        db.session.add(post)

        ##
        db.session.commit()
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)

    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))#?????????????
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    return render_template('index.html', form=form, posts=posts,
                           show_followed=show_followed, pagination=pagination)
示例#51
0
文件: vote.py 项目: EIREXE/WaifuSite
def vote(pk):
    print(pk)
    if not current_user:
        return redirect("/login")
    if request.method == 'GET':
        if pk + '_vote' in request.cookies:
            return redirect('/already_voted')
        redirect_to_index = redirect("/thankyou")
        response = current_app.make_response(redirect_to_index)
        response.set_cookie(pk + '_vote', value='true')
        waifu = current_app.dbbackend.get(Waifu, {"pk":pk})
        ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)

        try:
            if ip in waifu.votes_l:
                return redirect("/already_voted")
            waifu.votes_l.append(ip)
        except:
            waifu.votes_l = list()
            waifu.votes_l.append(ip)
        user_m = current_user._get_current_object()
        if waifu in user_m.voted_waifus:
                return redirect("/already_voted")
        user_m.voted_waifus.append(waifu)

        current_app.dbbackend.save(user_m)

        waifu.votes = waifu.votes + 1

        current_app.dbbackend.save(waifu)
        current_app.dbbackend.commit()
        current_app.dbbackend = FileBackend("./database")
    return response
示例#52
0
def post(id):
    post = Post.query.get_or_404(id)
    post.visits += int(1)
    print 'visit plus 1'

    form = CommentForm()

    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('评论提交成功')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count()-1) // \
            current_app.config['FLASKY_COMMENTS_PER_PAGE']+1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination,
                           post=post)
示例#53
0
文件: views.py 项目: heymars/flaskq
def index():
    form = QuestionForm()
    if current_user.can(Permission.ASK) and \
            form.validate_on_submit():
        question = Question(body=form.body.data,
                            detail=form.detail.data,
                            author=current_user._get_current_object())
        db.session.add(question)
        db.session.flush()
        question_activity = Activity(verb='asked', object=question,
                                  actor_id=current_user.id,
                                     timestamp=question.timestamp)
        db.session.add(question_activity)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_activities
    else:
        query = Activity.query
    pagination = query.order_by(Activity.timestamp.desc()).paginate(
            page, per_page=current_app.config['FLASKQ_ACTIVITIES_PER_PAGE'],
            error_out=False)
    activities = pagination.items
    comment_form = CommentForm()
    return render_template('index.html', form=form, activities=activities,
                           show_followed=show_followed, pagination=pagination,
                           comment_form=comment_form)
示例#54
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
            form.validate_on_submit():
        post = Post(body=form.body.data,
                    author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page,
        per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    return render_template('index.html',
                           form=form,
                           posts=posts,
                           show_followed=show_followed,
                           pagination=pagination)
示例#55
0
文件: views.py 项目: Ezio47/WebODM
def new():
    uploaded_files = request.files.getlist("file[]")
    filenames = []
    username = current_user.username
    label = request.form.get('label')
    # if this sequence name doesn't exist 
    if label is not None and not Sequence.query.filter_by(label=label, user_id=current_user.id).first():
        sequence = Sequence(label = label, user = current_user._get_current_object())
        for file in uploaded_files:
            # Check if the file is one of the allowed types/extensions
            if file and allowed_file(file.filename):
                # Make the filename safe, remove unsupported chars
                filename = secure_filename(file.filename)
                # Move the file form the temporal folder to the upload folder we setup
                #make user folder
                directory = current_app.config['UPLOAD_DEFAULT_DEST'] + username + '/' + label + '/' 
                if not os.path.exists(directory):
                    os.makedirs(directory + 'thumbs/')
                file.save(directory + filename)
                #create a thumbnail
                image = Image.open(directory + filename)
                image.thumbnail((158,116), Image.ANTIALIAS)
                image.save(directory + 'thumbs/' + filename, 'JPEG', quality=88)
                # Save the filename into a list, we'll use it later
                filenames.append(filename)
                #add photo to the database
                photo = Photo(file=filename, sequence = sequence)
                db.session.add(photo)
        db.session.add(sequence)
        db.session.commit()
        return redirect(url_for('.sequence', label = sequence.label, user=username))
    return render_template('new_sequence.html', filenames=filenames)
示例#56
0
文件: api.py 项目: tmzhuang/projecto
def create_item(project):
  path, err = _get_path()
  if err:
    return err

  try:
    File.get_by_project_path(project, path)
  except NotFoundError:
    is_directory = path.strip().endswith("/")
    data = {"path": path}
    if not is_directory:
      data["file"] = request.files.get("file", None)
      if not data["file"]:
        return abort(400)

    data["project"] = project
    data["author"] = current_user._get_current_object()
    f = File.create(data=data)
    try:
      f.save()
    except NotFoundError:
      return abort(404)

    return jsonify(**f.serialize_for_client())
  else:
    return jsonify(error="That path already exists!"), 400
示例#57
0
def post(id):
    post = Post.query.get_or_404(id)
    #Instantiate the comment form
    form = CommentForm()
    if form.validate_on_submit():
        #publishing the comment upon validation
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('Your comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    #Special page number to request the last page of comments to see on the page
    if page == -1:
        page = (post.comments.count() - 1) / \
            current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination)