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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With