Bird
Raised Fist0
Flaskframework~20 mins

Decorator for role requirement in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Role Requirement Decorator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask route with role check?
Consider this Flask route decorated with a role requirement decorator. What will be the HTTP response status code if the user role is 'guest'?
Flask
from flask import Flask, request, abort
app = Flask(__name__)

def role_required(role):
    def decorator(f):
        def wrapper(*args, **kwargs):
            user_role = request.headers.get('Role')
            if user_role != role:
                abort(403)
            return f(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/admin')
@role_required('admin')
def admin_panel():
    return 'Welcome Admin!'

# Assume a request to /admin with header Role: guest
A200 with body 'Welcome Admin!'
B403 Forbidden error
C404 Not Found error
D500 Internal Server Error
Attempts:
2 left
💡 Hint
Think about what happens when the user role does not match the required role.
📝 Syntax
intermediate
2:00remaining
Which decorator syntax correctly preserves function metadata?
You want to create a role_required decorator that preserves the original function's name and docstring. Which option correctly uses functools.wraps?
Flask
from functools import wraps

def role_required(role):
    def decorator(f):
        # Choose the correct wrapper implementation
        pass
    return decorator
A
def wrapper(*args, **kwargs):
    if user_role != role:
        abort(403)
    return f(*args, **kwargs)

return wrapper
B
def wrapper(*args, **kwargs):
    if user_role != role:
        abort(403)
    @wraps(f)
    return f(*args, **kwargs)

return wrapper
C
def wrapper(*args, **kwargs):
    @wraps(f)
    if user_role != role:
        abort(403)
    return f(*args, **kwargs)

return wrapper
D
@wraps(f)
def wrapper(*args, **kwargs):
    if user_role != role:
        abort(403)
    return f(*args, **kwargs)

return wrapper
Attempts:
2 left
💡 Hint
functools.wraps is used as a decorator on the wrapper function.
🔧 Debug
advanced
2:00remaining
Why does this role_required decorator cause a runtime error?
Examine this decorator code. What causes the runtime error when calling the decorated function?
Flask
def role_required(role):
    def decorator(f):
        def wrapper(*args, **kwargs):
            user_role = request.headers.get('Role')
            if user_role != role:
                abort(403)
            return f
        return wrapper
    return decorator
AThe decorator does not accept *args and **kwargs, causing a TypeError.
BThe abort function is called without importing it, causing a NameError.
CThe wrapper returns the function object f instead of calling it, causing a TypeError later.
DThe user_role variable is not defined, causing a NameError.
Attempts:
2 left
💡 Hint
Look at what the wrapper returns after the role check.
🧠 Conceptual
advanced
1:30remaining
What is the main purpose of using a decorator for role requirement in Flask?
Why do developers use decorators like role_required in Flask applications?
ATo add reusable access control logic to routes without repeating code.
BTo automatically generate HTML templates for different user roles.
CTo improve database query performance by caching role data.
DTo replace Flask's built-in routing system with custom routing.
Attempts:
2 left
💡 Hint
Think about how decorators help with code reuse and separation of concerns.
❓ state_output
expert
2:30remaining
What is the output of this Flask app with nested role_required decorators?
Given this Flask app code, what will be the response body when a request with header Role: admin accesses /dashboard?
Flask
from flask import Flask, request, abort
app = Flask(__name__)

def role_required(role):
    def decorator(f):
        def wrapper(*args, **kwargs):
            user_role = request.headers.get('Role')
            if user_role != role:
                abort(403)
            return f(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/dashboard')
@role_required('admin')
@role_required('user')
def dashboard():
    return 'Dashboard Accessed'

# Request header: Role: admin
A403 Forbidden error
B200 OK with body 'Dashboard Accessed'
C500 Internal Server Error
D404 Not Found error
Attempts:
2 left
💡 Hint
Consider the order decorators are applied and how role checks happen.

Practice

(1/5)
1. What is the main purpose of a decorator that checks user roles in a Flask app?
easy
A. To log user activity without restrictions
B. To speed up the execution of functions
C. To change the user role dynamically
D. To restrict access to certain functions based on user roles

Solution

  1. Step 1: Understand the role of decorators in Flask

    Decorators wrap functions to add extra behavior, like checking conditions before running the function.
  2. Step 2: Identify the purpose of role checking

    Role checking ensures only users with the right permissions can access certain parts of the app.
  3. Final Answer:

    To restrict access to certain functions based on user roles -> Option D
  4. Quick Check:

    Role check decorator = restrict access [OK]
Hint: Decorators add checks before function runs [OK]
Common Mistakes:
  • Thinking decorators change user roles
  • Assuming decorators speed up code
  • Confusing logging with access control
2. Which of the following is the correct syntax to define a decorator that requires a role named 'admin' in Flask?
easy
A. @require_role(admin)\ndef admin_panel():\n pass
B. def require_role('admin'):\n def admin_panel():\n pass
C. @require_role('admin')\ndef admin_panel():\n pass
D. @require_role['admin']\ndef admin_panel():\n pass

Solution

  1. Step 1: Recognize decorator syntax in Python

    Decorators use @ followed by the decorator function call with parentheses if it takes arguments.
  2. Step 2: Check correct argument passing

    The role name 'admin' must be passed as a string inside parentheses.
  3. Final Answer:

    @require_role('admin')\ndef admin_panel():\n pass -> Option C
  4. Quick Check:

    Decorator with parentheses and string argument = correct [OK]
Hint: Decorator with argument uses parentheses and quotes [OK]
Common Mistakes:
  • Missing parentheses for decorator with arguments
  • Passing role without quotes
  • Using square brackets instead of parentheses
3. Given this decorator code snippet, what will be printed when a user with role 'user' tries to access the decorated function?
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'))
medium
A. Secret Info
B. Access Denied
C. TypeError
D. None

Solution

  1. 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'.
  2. Step 2: Analyze the function call with 'user' role

    The user_role 'user' does not match 'admin', so the wrapper returns 'Access Denied'.
  3. Final Answer:

    Access Denied -> Option B
  4. Quick Check:

    User role mismatch = Access Denied [OK]
Hint: Mismatch role returns 'Access Denied' [OK]
Common Mistakes:
  • Assuming function runs regardless of role
  • Confusing return values
  • Ignoring wrapper function logic
4. Identify the error in this Flask role-checking decorator code:
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 decorator
medium
A. Missing return statement before func call inside wrapper
B. Incorrect use of *args and **kwargs
C. current_user.role should be current_user.roles
D. Decorator should not have nested functions

Solution

  1. 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.
  2. Step 2: Confirm correct fix

    Adding 'return' before func call ensures the wrapper returns the function's output properly.
  3. Final Answer:

    Missing return statement before func call inside wrapper -> Option A
  4. Quick Check:

    Always return function result in wrapper [OK]
Hint: Wrapper must return the wrapped function's result [OK]
Common Mistakes:
  • Forgetting to return function output
  • Misusing argument unpacking
  • Incorrect attribute name for user role
5. You want to create a Flask decorator that allows access if the user role is either 'admin' or 'editor'. Which of these decorator implementations correctly achieves this?
hard
A. def require_roles(*roles): def decorator(func): def wrapper(user_role): if user_role in roles: return func() return 'Access Denied' return wrapper return decorator @require_roles('admin', 'editor') def edit_page(): return 'Edit Page'
B. def require_roles(roles): def decorator(func): def wrapper(user_role): if user_role == roles: return func() return 'Access Denied' return wrapper return decorator @require_roles(['admin', 'editor']) def edit_page(): return 'Edit Page'
C. def require_roles(*roles): def decorator(func): def wrapper(user_role): if user_role == roles: return func() return 'Access Denied' return wrapper return decorator @require_roles('admin', 'editor') def edit_page(): return 'Edit Page'
D. def require_roles(roles): def decorator(func): def wrapper(user_role): if user_role in roles: func() return 'Access Denied' return wrapper return decorator @require_roles(['admin', 'editor']) def edit_page(): return 'Edit Page'

Solution

  1. Step 1: Understand how to accept multiple roles

    Using *roles collects multiple role arguments as a tuple, allowing easy membership checks.
  2. 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'.
  3. Final Answer:

    Implementation using *roles and 'in' check with return func() -> Option A
  4. Quick Check:

    Use *args and 'in' for multiple roles [OK]
Hint: Use *args and 'in' to check multiple roles [OK]
Common Mistakes:
  • Comparing user_role to tuple instead of membership
  • Not returning function result
  • Passing roles as list but comparing with == instead of 'in'
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard