Error Pages in Flask

If we want to control errors within our applications, we must know how to manage our error pages in Flask. What we need to know is how to return one error code or another.

The first thing we need to know to control our error pages in Flask is that we are going to need the abort() method. That is why the first thing will be to recover it from our framework Flask.

from flask import Flask, abort

Now the next thing will be to use the abort() method in conjunction with one of the HTTP error codes as a parameter:

  • 401, unauthorized.
  • 403, prohibited.
  • 404, not found.
  • 405, method not allowed.

For example, we could control access to a page using the following code:

@app.route('/blocked')
def locked():
    return abort(401)

Or indicate that there is a method that is not supported:

@app.route('/request',methods=['POST'])
def request():
    return abort(405)

We see that it is always indicating the abort() method with the associated error code and returning the information as a response.

So we have already seen how simple it is to manage the Error pages in Flask. Of course, the standard error pages.

Leave a Comment