A decorator for role requirement helps control who can access certain parts of a web app based on their role. It keeps your code clean and secure by checking user roles before running a function.
Decorator for role requirement in Flask
from functools import wraps def role_required(role): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if current_user.role != role: return "Access denied", 403 return func(*args, **kwargs) return wrapper return decorator
The outer function role_required takes the role name as input.
The inner decorator wraps the original function to add role checking.
admin_panel function so only users with role 'admin' can access it.@role_required('admin') def admin_panel(): return "Welcome Admin"
edit_article function to users with role 'editor'.@role_required('editor') def edit_article(): return "Edit your article here"
This Flask example shows a simple role check decorator. The current_user is mocked as an admin. The admin_panel route allows access, but edit_article denies access because the user is not an editor.
from flask import Flask from functools import wraps app = Flask(__name__) # Mock current_user for demo class User: def __init__(self, role): self.role = role current_user = User('admin') def role_required(role): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if current_user.role != role: return "Access denied", 403 return func(*args, **kwargs) return wrapper return decorator @app.route('/admin') @role_required('admin') def admin_panel(): return "Welcome Admin" @app.route('/edit') @role_required('editor') def edit_article(): return "Edit your article here" # Simulate calling routes print(admin_panel()) print(edit_article())
Make sure current_user correctly represents the logged-in user in your real app.
You can extend the decorator to accept multiple roles or check permissions more flexibly.
Decorators can check user roles before running a function.
This keeps your code clean and secure by centralizing role checks.
Use it to protect routes or functions based on user roles.
Practice
Solution
Step 1: Understand the role of decorators in Flask
Decorators wrap functions to add extra behavior, like checking conditions before running the function.Step 2: Identify the purpose of role checking
Role checking ensures only users with the right permissions can access certain parts of the app.Final Answer:
To restrict access to certain functions based on user roles -> Option DQuick Check:
Role check decorator = restrict access [OK]
- Thinking decorators change user roles
- Assuming decorators speed up code
- Confusing logging with access control
Solution
Step 1: Recognize decorator syntax in Python
Decorators use @ followed by the decorator function call with parentheses if it takes arguments.Step 2: Check correct argument passing
The role name 'admin' must be passed as a string inside parentheses.Final Answer:
@require_role('admin')\ndef admin_panel():\n pass -> Option CQuick Check:
Decorator with parentheses and string argument = correct [OK]
- Missing parentheses for decorator with arguments
- Passing role without quotes
- Using square brackets instead of parentheses
def require_role(role):
def decorator(func):
def wrapper(user_role):
if user_role == role:
return func()
else:
return 'Access Denied'
return wrapper
return decorator
@require_role('admin')
def secret_data():
return 'Secret Info'
print(secret_data('user'))Solution
Step 1: Understand the decorator logic
The wrapper checks if the passed user_role matches the required role 'admin'. If yes, it calls the function; otherwise, returns 'Access Denied'.Step 2: Analyze the function call with 'user' role
The user_role 'user' does not match 'admin', so the wrapper returns 'Access Denied'.Final Answer:
Access Denied -> Option BQuick Check:
User role mismatch = Access Denied [OK]
- Assuming function runs regardless of role
- Confusing return values
- Ignoring wrapper function logic
def require_role(role):
def decorator(func):
def wrapper(*args, **kwargs):
if current_user.role == role:
func(*args, **kwargs)
else:
return 'Forbidden'
return wrapper
return decoratorSolution
Step 1: Check the wrapper function's return behavior
The wrapper calls func(*args, **kwargs) but does not return its result, so the decorated function returns None.Step 2: Confirm correct fix
Adding 'return' before func call ensures the wrapper returns the function's output properly.Final Answer:
Missing return statement before func call inside wrapper -> Option AQuick Check:
Always return function result in wrapper [OK]
- Forgetting to return function output
- Misusing argument unpacking
- Incorrect attribute name for user role
Solution
Step 1: Understand how to accept multiple roles
Using *roles collects multiple role arguments as a tuple, allowing easy membership checks.Step 2: Check membership and return function result
The wrapper checks if user_role is in roles and returns func() result; otherwise returns 'Access Denied'.Final Answer:
Implementation using *roles and 'in' check with return func() -> Option AQuick Check:
Use *args and 'in' for multiple roles [OK]
- Comparing user_role to tuple instead of membership
- Not returning function result
- Passing roles as list but comparing with == instead of 'in'
Ready to prove it?
Pass the test and this pattern moves unknown
