Troubleshooting Guide

I am new to writing a flask and am currently using flask-principal as my authorization mechanism. When a user tries to access the URL without the necessary permission, the flag raise raises a PermissionDenied Exception.

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

How can I catch a specific exception and redirect the user to the warning page? If you can share some sample code, this will be very helpful.

+6
source share
1 answer

You can tell Flask-Principal that you want to raise the 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 error code 403, you can 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') will return the route url for the login page.

+8
source

Source: https://habr.com/ru/post/958380/


All Articles