其原理是在python脚本hello.py中调用处理错误的路由,定义相应情况下的视图函数,然后当浏览地址出现错误时,就调用定义的函数,显示对应的模板中定义的内容。
第一步,在hello.py 中自定义错误页面的处理程序
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
第二步,处理错误时显示的模板
将之前的user.html文件稍作修改:
{% block content %}
<div class="container">
{% block page_content %}{% endblock %}
#一个空块容器,页面内容在衍生模板中定义
</div>
{% endblock %}
保存,作为基模板,后面的404.html和500.html都从这个模板衍生而来。同时,user.html也可以改成以这个文件为基模板的衍生模板。
第三步,用Jinja2的模板继承机制自定义404错误页面、
{% extends "base.html" %}
{% block title %}Flasky - Page Not Found{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Not Found</h1>
</div>
{% endblock %}
保存成404.html到templates文件夹中。
第四步,服务器跑起来,到浏览器中测试
这个其实也就是Jinja2模板的一个应用,只是调用了路由@app中的函数(or 模块?)errorhandler而已。对于这个牛逼的Bootstrap框架,恐怕只能算是惊鸿一瞥。