本节的内容非常轻松,管理评论;具有Moderate权限的用户,可以控制评论的显示和隐藏;
app/template/base.html 在导航栏中加入管理评论链接:
...
<ul class="nav navbar-nav navbar-right">
{% if current_user.can(Permission.MODERATE) %}
<li><a href="{{ url_for('main.moderate') }}">Moderate Comments</a></li>
{% endif %}
</ul>
app/main/views.py 管理评论的路由:
@main.route('/moderate')
@login_required
@permission_required(Permission.MODERATE)
def moderate():
page = request.args.get('page', 1, type=int)
pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(
page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'], error_out=False)
comments = pagination.items
return render_template('moderate.html', comments=comments, pagination=pagination, page=page)
它从数据库中读取一页评论,将其传入模板进行渲染,除了评论列表之外,还把分页对象和当前页数传入了模板。
app/templates/moderate.html 评论管理页面的模板
{% extends 'base.html' %}
{% import "_macros.html" as macros %}
{% block title %}Flasky - Comment Moderate{% endblock %}
{% block page_content %}
<div class="page-header text-primary"><h1>Comment Moderate</h1></div>
{% set moderate = True %}
{% include '_comments.html' %}
{% if pagination %}
<div class="pagination">{{ macros.pagination_widget(pagination, '.moderate') }}</div>
{% endif %}
{% endblock %}
这个模板将渲染评论的工作交给_comments.html模板完成,但把控制权交给从模板之前,会使用JInjia2提供的set指令定义一个模板变量moderate,并将其设为True。这个变量用在_comments.html模板中,决定是否渲染评论管理功能。
app/template/_comments.html:渲染评论正文
...
<div class="comment-body">
{% if comment.disabled %}
<p class="text-danger"><i>This Comment has been disabled by a moderator.</i></p>
{% endif %}
{% if moderate or not comment.disabled %}
{% if comment.body_html %}
{{ comment.body_html | safe }}
{% else %}
{{ comment.body }}
{% endif %}
{% endif %}
</div>
{% if moderate %}
<br>
{% if comment.disabled %}
<a class="btn btn-default btn-xs" href="{{ url_for('.moderate_enable', id=comment.id, page=page) }}">Enable</a>
{% else %}
<a class="btn btn-danger btn-xs" href="{{ url_for('.moderate_disable', id=comment.id, page=page) }}">Disable</a>
{% endif %}
{% endif %}
...
上述模板涉及2个评论管理路由:“main.moderate_enable”和“main.moderate_disable”:
@main.route('/moderate/enable/<int:id>')
@login_required
@permission_required(Permission.MODERATE)
def moderate_enable(id):
comment = Comment.query.get_or_404(id)
comment.disabled = False
db.session.commit()
return redirect(url_for('.moderate', page=request.args.get('page', 1, type=int)))
@main.route('/moderate/disable/<int:id>')
@login_required
@permission_required(Permission.MODERATE)
def moderate_disable(id):
comment = Comment.query.get_or_404(id)
comment.disabled = True
db.session.commit()
return redirect(url_for('.moderate', page=request.args.get('page', 1, type=int)))
至此,关于博客程序的介绍已经完毕,下一章我们将讨论如何以API的形式开放应用功能,供智能手机应用等客户端使用。