When you’ve finished reading How to implement Python Decorators you might wonder if it is possible to hand over some parameters to the decorator function. And yes that is possible and can come in quite handy.
For a Flask project I wrote a decorator to manage authorization of endpoints. I wanted to grant access to a certain endpoint only when a the necessary role was present in the user database.
In case the user hadn’t the correct rights the 403 page would be rendered.
The decorator is implemented this way:
def requires_role(*necessary_roles):
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
user_roles = current_user.get_roles().split(", ")
role_present = False
for role in necessary_roles[0].split(", "):
if role in user_roles:
role_present = True
if not role_present:
abort(403)
return f(*args, **kwargs)
return wrapped
return wrapper
Now you can use it this way:
@requires_role("admin")
@app.route("/admin")
def admin():
return render_template('admin.html')