Bird
Raised Fist0
Flaskframework~20 mins

Before_request hooks in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Before_request Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a before_request hook returns a response?
Consider a Flask app with a before_request hook that returns a response object. What will Flask do next?
Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.before_request
def check():
    return jsonify({'error': 'blocked'})

@app.route('/')
def home():
    return 'Welcome!'

# What will be the output when accessing '/'?
AThe 'home' route runs and returns 'Welcome!'
BThe before_request response is sent; 'home' route is skipped
CFlask raises an error because before_request returned a response
DThe before_request hook runs after the 'home' route
Attempts:
2 left
💡 Hint
Think about what happens if a before_request returns a response instead of None.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this before_request hook
Which option contains a syntax error in defining a Flask before_request hook?
Flask
from flask import Flask
app = Flask(__name__)

@app.before_request
def check():
    print('Checking request')

@app.route('/')
def home():
    return 'Hello!'
A
@app.before_request
def check():
    print('Checking request')
B
@app.before_request()
def check():
    print('Checking request')
C
@app.before_request
def check:
    print('Checking request')
D
)'tseuqer gnikcehC'(tnirp    
:)(kcehc fed
tseuqer_erofeb.ppa@
Attempts:
2 left
💡 Hint
Check function definition syntax carefully.
❓ state_output
advanced
2:00remaining
How many times does the before_request hook run on multiple requests?
Given this Flask app, how many times will the before_request hook run after 3 separate HTTP GET requests to '/'?
Flask
from flask import Flask
app = Flask(__name__)
counter = 0

@app.before_request
def increment():
    global counter
    counter += 1

@app.route('/')
def home():
    return f'Count: {counter}'
A3 times total, once per request
B1 time total, because the app runs once
C0 times, before_request hooks don't run automatically
DDepends on the number of routes, so 1 time
Attempts:
2 left
💡 Hint
Think about when before_request hooks run in relation to each HTTP request.
🔧 Debug
advanced
2:00remaining
Why does this before_request hook not block unauthorized access?
This Flask app tries to block access if a header is missing, but unauthorized users still get through. Why?
Flask
from flask import Flask, request, abort
app = Flask(__name__)

@app.before_request
def check_auth():
    if 'X-Auth' not in request.headers:
        abort(403)

@app.route('/')
def home():
    return 'Welcome!'
Aabort() is not imported from flask
Babort(403) is called but the route still runs
Cbefore_request hook is not registered correctly
Dabort(403) raises an exception that stops the request
Attempts:
2 left
💡 Hint
Consider what abort(403) does in Flask.
🧠 Conceptual
expert
2:00remaining
Order of execution with multiple before_request hooks
Given two before_request hooks in this Flask app, in what order do they run?
Flask
from flask import Flask
app = Flask(__name__)

@app.before_request
def first():
    print('First hook')

@app.before_request
def second():
    print('Second hook')

@app.route('/')
def home():
    return 'Done'
AFirst hook runs, then second hook
BOnly the last defined hook runs
CHooks run in random order
DSecond hook runs, then first hook
Attempts:
2 left
💡 Hint
Think about the order decorators are applied in Python.

Practice

(1/5)
1. What is the main purpose of a before_request hook in Flask?
easy
A. To run code before every request to prepare or check something
B. To define the main route of the application
C. To handle errors after a request is processed
D. To send the final response to the client

Solution

  1. Step 1: Understand the role of before_request

    The before_request hook runs before each request to prepare data or check conditions.
  2. Step 2: Compare with other options

    Defining routes, handling errors, or sending responses happen elsewhere, not in before_request.
  3. Final Answer:

    To run code before every request to prepare or check something -> Option A
  4. Quick Check:

    before_request runs before request = C [OK]
Hint: before_request runs code before each request [OK]
Common Mistakes:
  • Confusing before_request with route handlers
  • Thinking it handles errors or sends responses
  • Assuming it runs after the request
2. Which of the following is the correct way to register a before_request hook in Flask that does not short-circuit the request?
easy
A. @app.before_request\nclass BeforeHook: pass
B. @app.before_request()\ndef before(): pass
C. @app.before_request\ndef before(): return 'Hello'
D. @app.before_request\ndef before(): pass

Solution

  1. Step 1: Recall the decorator syntax

    The before_request decorator is used without parentheses: @app.before_request.
  2. Step 2: Check function definition

    The hook must be a function, not a class, and must not return a response to continue to the route.
  3. Final Answer:

    @app.before_request\ndef before(): pass -> Option D
  4. Quick Check:

    Decorator without () and function = D [OK]
Hint: Use @app.before_request without parentheses [OK]
Common Mistakes:
  • Adding parentheses after @app.before_request
  • Defining a class instead of a function
  • Returning a value when not needed
3. Given this Flask code, what will be the output when accessing /?
from flask import Flask, redirect
app = Flask(__name__)

@app.before_request
def check():
    return redirect('/login')

@app.route('/')
def home():
    return 'Home Page'

@app.route('/login')
def login():
    return 'Login Page'
medium
A. Home Page
B. Login Page
C. Redirect loop error
D. 404 Not Found

Solution

  1. Step 1: Analyze the before_request hook

    The check function unconditionally returns a redirect to /login for every request.
  2. Step 2: Determine the final response

    Request to / redirects to /login, but /login also triggers before_request which redirects again, causing an infinite loop.
  3. Final Answer:

    Redirect loop error -> Option C
  4. Quick Check:

    Always redirect to /login = C [OK]
Hint: Unconditional return in before_request causes loop [OK]
Common Mistakes:
  • Expecting 'Login Page' without considering loop
  • Thinking before_request does not run on /login
  • Ignoring that every request triggers the hook
4. What is wrong with this Flask code snippet?
from flask import Flask
app = Flask(__name__)

@app.before_request
def before():
    print('Before request')
    return None

@app.route('/')
def index():
    return 'Hello'
medium
A. before_request must return a response always
B. Nothing is wrong; code works fine
C. Printing inside before_request is not allowed
D. Returning None in before_request causes an error

Solution

  1. Step 1: Understand return behavior in before_request

    Returning None means no response is sent, so Flask continues to route handler.
  2. Step 2: Check if printing is allowed

    Printing is allowed and useful for debugging; it does not cause errors.
  3. Final Answer:

    Nothing is wrong; code works fine -> Option B
  4. Quick Check:

    None return means continue normal route = A [OK]
Hint: Return None or nothing to continue request normally [OK]
Common Mistakes:
  • Thinking return None causes error
  • Believing before_request must always return response
  • Assuming print statements break Flask hooks
5. You want to use a before_request hook to block access to all routes except /login unless a user is logged in. Which code snippet correctly implements this?
hard
A. from flask import request, redirect, session @app.before_request def block(): if request.path != '/login' and not session.get('user'): return redirect('/login')
B. from flask import request, redirect @app.before_request def block(): if request.path == '/login': return redirect('/login')
C. from flask import session @app.before_request def block(): if not session.get('user'): return 'Access Denied'
D. from flask import request @app.before_request def block(): if request.path == '/login' or session.get('user'): return redirect('/login')

Solution

  1. Step 1: Identify the condition to block access

    We want to redirect to /login if the path is not /login and user is not logged in.
  2. Step 2: Check each option logic

    from flask import request, redirect, session @app.before_request def block(): if request.path != '/login' and not session.get('user'): return redirect('/login') correctly checks path and session, redirecting only when needed. Others either redirect wrongly or deny access without redirect.
  3. Final Answer:

    from flask import request, redirect, session @app.before_request def block(): if request.path != '/login' and not session.get('user'): return redirect('/login') -> Option A
  4. Quick Check:

    Check path and session, redirect if not logged in = A [OK]
Hint: Check path and session, redirect if not logged in [OK]
Common Mistakes:
  • Redirecting /login to itself causing loop
  • Not checking path before redirect
  • Returning string instead of redirect response
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