9

I am new in writing flask and currently use flask-principal as my authorization mechanism. When a user tries to access a url without the required permission, flask-principal raises a PermissionDenied Exception.

It causes my system to throw a 500 internal server error.

How could I catch the specific exception and redirect user to a warning page instead? If you could share a code example, that will be very helpful.

codegeek
  • 32,236
  • 12
  • 63
  • 63
Theon Lin
  • 330
  • 3
  • 8

1 Answers1

18

You can tell Flask-Principal that you want to raise a specific HTTP error code instead:

@app.route('/admin')
@admin_permission.require(http_exception=403)
def admin(request):
    # ...

Now flask.abort() will be called instead of raising PermissionDenied. For the 403 error code you can then register an error handler:

@app.errorhandler(403)
def page_not_found(e):
    session['redirected_from'] = request.url
    return redirect(url_for('users.login'))

where url_for('users.login') would return the route URL for a login page.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343