Flask-如何抛出错误以及自定义错误处理方法?

1、抛出错误

  • abort()函数
  • 只能抛出HTTP协议规定的状态码
  • 示例:
    from flask import request,render_template,abort @app.route('/login',methods = ['GET','POST']) def login(): if request.method = 'POST': if '_xsrf' not in request.form: abort(403) return render_template('login.html')

2、错误处理

  • 使用errorhandler装饰器,当程序抛出指定错误状态码或异常的时候,就会调用该装饰器所装饰的方法
  • 接收的参数为HTTP的错误状态码或指定异常
  • 示例:
    from flask import render_template #错误状态码404的处理
    @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404
    
    # 处理特定的异常项
    @app.errorhandler(ZeroDivisionError) def zero_division_error(e): return '除数不能为0'
相关文章
相关标签/搜索