Python Flask学习_自定义错误界面

在之前学习过响应错误界面,使用的是abort函数:点击打开链接

  1. @app.route('/user/<name>')  
  2. def user(name):  
  3.     if name !='chen':        #如果name != 'chen'  
  4.         abort(404)           #由abort函数生成404错误响应  
  5.     return '<h1> Hello,%s </h1>'% name  

但是,Flask允许程序使用基于模板的自定义错误界面,自定义生成html文档的方式已经介绍过了:点击打开链接

下面重点讲,在python中如何定义响应错误界面的视图函数

# test.py

@app.errorhandler(404)                            #使用app.errorhandler装饰器,传入错误码404
def page_not_found(e):
    return render_template('404.html'),404        #返回响应文档404.html,状态码404.(下同)

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'),500

猜你喜欢

转载自blog.csdn.net/bird333/article/details/80717810