重定向和错误
使用 redirect()
函数可以重定向。使用 abort()
可以 更早退出请求,并返回错误代码。
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
上例实际上是没有意义的,它让一个用户从索引页重定向到一个无法访问的页面(401 表示禁止访问)。但是上例可以说明重定向和出错跳出是如何工作的。
自定义错误处理方法
使用 errorhandler()
装饰器可以定制出错页面:
from flask import render_template
# 自定义404错误处理视图
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
注意 render_template() 后面的 404 ,这表示页面对就的出错 代码是 404 ,即页面不存在。缺省情况下 200 表示:一切正常
使用 register_error_handler()
装饰器可以定制出错页面:
app.register_error_handler(400, handle_bad_request)
消息闪现
一个好的应用和用户界面都需要良好的反馈。如果用户得不到足够的反馈,那么应用最终会被用户唾弃。 Flask 的闪现系统提供了一个良好的反馈方式。闪现系统的基 本工作方式是:在且只在下一个请求中访问上一个请求结束时记录的消息
。一般我们 结合布局模板来使用闪现系统。注意,浏览器会限制 cookie 的大小,有时候网络服务器也会。这样如果消息比会话 cookie 大的话,那么会导致消息闪现静默失败。
flash()
用于闪现一个消息。在模板中,使用 get_flashed_messages()
来操作消息
简单的例子
from flask import Flask, flash, redirect, render_template, \
request, url_for
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'secret':
error = 'Invalid credentials'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error)
以下是实现闪现的 layout.html 模板
<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}{% endblock %}
以下是继承自 layout.html 的 index.html 模板:
{% extends "layout.html" %}
{% block body %}
<h1>Overview</h1>
<p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}
以下是同样继承自 layout.html 的 login.html 模板:
{% extends "layout.html" %}
{% block body %}
<h1>Login</h1>
{% if error %}
<p class=error><strong>Error:</strong> {{ error }}
{% endif %}
<form method=post>
<dl>
<dt>Username:
<dd><input type=text name=username value="{{
request.form.username }}">
<dt>Password:
<dd><input type=password name=password>
</dl>
<p><input type=submit value=Login>
</form>
{% endblock %}
闪现消息的类别
闪现消息还可以指定类别,如果没有指定,那么缺省的类别为 ‘message
’ 。不同的 类别可以给用户提供更好的反馈。例如错误消息可以使用红色背景。
使用 flash()
函数可以指定消息的类别:
flash(message, category=‘message’)
- message:要闪现的消息内容
- category:’
message
'适用于任何类型的消息, 'error
‘错误,’info
‘信息消息和’warning
'警告
flash(u'Invalid password provided', 'error')
模板中的 get_flashed_messages()
函数也应当返回类别,显示消息的循环 也要略作改变。
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class=flashes>
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
上例展示如何根据类别渲染消息,还可以给消息加上前缀,如 <strong>Error:{{ message }}</strong>
过滤闪现消息
你可以视情况通过传递一个类别列表来过滤 get_flashed_messages() 的 结果。这个功能有助于在不同位置显示不同类别的消息。
{% with errors = get_flashed_messages(category_filter=["error"]) %}
{% if errors %}
<div class="alert-message block-message error">
<a class="close" href="#">×</a>
<ul>
{%- for msg in errors %}
<li>{{ msg }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% endwith %}