flask exception

 flask exception

 

1.1.    abort

The concept: flask in exception handling statement, similar to the function in python raise statement, as long as the trigger abort, the code behind will not be executed, abort can only throw an exception status code in line with the http protocol.

from werkzeug.exceptions import abort

@app.route('/abort')
def view_abort():
    abort(405)
    return 'abort test from main route'

 

1.2.    errorhandler

errorhandler decorated with abort function is used, in order to further enhance the user experience, he received was thrown exception abort function status code, custom error pages and information.

 

@app.route('/abort')
def view_abort():
    abort(405)
    return 'abort test from main route'

@app.errorhandler(405)
def err_404(e):
    return '错误404' + str(e)

 

Error handling There are two types: global and non-global

If the blueprint, then the following this non-global. The result is no difference without a blueprint.

@blue_t.errorhandler(405)
def err_405(e):
    print('err_405')
    return 'error 405 from blueprint blue_t'

 

app_errorhandler () is global

@blue_t.app_errorhandler(405)
def err_404(e):
    return 'blueprint error_405'
    #return render_template('error/404.html')

 

When we are not using a factory pattern to create the app, app.errorhandler (401), to capture the global state 401; if the app is created using create_app way, you can not capture, if you want to capture, you can write in the blueprint, such as admin .errorhandler (401), i.e., the status code 401 to capture all the admin blueprint, admin.app_errorhandler (401), is to capture the global status code 401, i.e. state 401 other blueprint, it will be captured, processed

 

Note: handler after handler execution will overwrite the first statement.

Example:

app.py

@app.errorhandler(405)
def err_404(e):
    print('main:err_404')
    return '错误404' + str(e)

Blueprint statement

@blue_t.app_errorhandler(405)
def err_404(e):
    return 'blueprint error_405'
   
#return render_template('error/404.html')

Access / abort will jump to the blueprint errorhandler.

2. summary

Exception handling using @ blueprint.errorhandler blueprint ()

 

Top app in exception handling concentrated and then call the function.

# 异常处理
def register_errors(app):
    @app.errorhandler(405)
    def method_not_allowed(e):
        return api_abort(405, message='The method is not allowed for the requested URL.')

 

Guess you like

Origin www.cnblogs.com/wodeboke-y/p/11093538.html