Bird
Raised Fist0
Flaskframework~20 mins

Before_request as middleware alternative in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask 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 Flask before_request function returns a response?

In Flask, if a before_request function returns a response, what is the effect on the request processing?

Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.before_request
def check_auth():
    return jsonify({'error': 'Unauthorized'}), 401

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

# What will a client see when accessing '/'?
AThe client receives a 401 JSON error response and the home route is not executed.
BThe client receives an empty response with status 200.
CThe client receives a 500 Internal Server Error due to returning a response in before_request.
DThe client receives 'Welcome!' because the before_request does not affect the route.
Attempts:
2 left
💡 Hint

Think about how Flask handles returned responses in before_request functions.

📝 Syntax
intermediate
2:00remaining
Identify the correct way to register a before_request function in Flask

Which of the following code snippets correctly registers a before_request function in Flask?

A
def check():
    pass
app.before_request(check)
B
@app.before_request()
def check():
    pass
C
@app.before_request
check = lambda: None
D
@app.before_request
def check():
    pass
Attempts:
2 left
💡 Hint

Remember the decorator syntax for Flask hooks.

🔧 Debug
advanced
2:00remaining
Why does this Flask before_request middleware not block unauthorized access?

Consider this Flask app code:

from flask import Flask, request
app = Flask(__name__)

@app.before_request
def check_token():
    token = request.headers.get('Authorization')
    if token != 'secret':
        return None

@app.route('/data')
def data():
    return 'Sensitive data'

Why might a client still access '/data' without the correct token?

ABecause the before_request function does not return a response object, Flask ignores it.
BBecause the route '/data' is registered before the before_request function.
CBecause the before_request function returns a string and status code tuple, which Flask accepts and blocks access correctly.
DBecause the client is sending the correct token, so access is allowed.
Attempts:
2 left
💡 Hint

Check the return type of the before_request function when blocking access.

❓ state_output
advanced
2:00remaining
What is the output when using before_request to modify g object in Flask?

Given this Flask app code:

from flask import Flask, g
app = Flask(__name__)

@app.before_request
def set_user():
    g.user = 'Alice'

@app.route('/')
def home():
    return f'Hello, {g.user}!'

What will a client see when accessing '/'?

AHello, !
BHello, Alice!
CAttributeError because g.user is not set
D500 Internal Server Error due to missing return
Attempts:
2 left
💡 Hint

Think about how Flask's g object works across requests.

🧠 Conceptual
expert
3:00remaining
How does Flask's before_request compare to middleware in other frameworks?

Which statement best describes the difference between Flask's before_request functions and middleware in frameworks like Express.js or Django?

AFlask's before_request functions are identical to middleware in Express.js and Django, supporting next() calls to pass control.
BFlask does not support middleware; before_request is the only way to intercept requests.
CFlask's before_request functions are simpler hooks that run before each request but do not form a chain of middleware layers like Express.js middleware.
DFlask's before_request functions run after the response is sent, unlike middleware in other frameworks.
Attempts:
2 left
💡 Hint

Consider how control flow works in Flask before_request vs middleware chains.

Practice

(1/5)
1. What is the main purpose of the before_request function in Flask?
easy
A. To send the final response to the client
B. To handle errors after a request has been processed
C. To define routes and their handlers
D. To run code before every request to perform tasks like login checks or logging

Solution

  1. Step 1: Understand the role of before_request

    The before_request function runs before each request to the Flask app, allowing pre-processing like login checks or logging.
  2. Step 2: Compare with other Flask functions

    Functions like error handlers run after requests, and route handlers define endpoints, so they differ from before_request.
  3. Final Answer:

    To run code before every request to perform tasks like login checks or logging -> Option D
  4. Quick Check:

    before_request runs before requests = D [OK]
Hint: before_request runs code before requests start [OK]
Common Mistakes:
  • Confusing before_request with error handlers
  • Thinking before_request sends responses directly
  • Mixing route definition with before_request
2. Which of the following is the correct way to register a before_request function in Flask?
easy
A. @app.before_request\ndef my_function(): pass
B. app.before_request(my_function())
C. app.before_request = my_function()
D. app.before_request = my_function

Solution

  1. Step 1: Recall Flask decorator syntax

    Flask uses decorators like @app.before_request above a function to register it as a before_request handler.
  2. Step 2: Analyze each option

    @app.before_request\ndef my_function(): pass uses the correct decorator syntax. app.before_request(my_function()) calls the function instead of decorating. Options C and D assign incorrectly.
  3. Final Answer:

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

    Use @app.before_request decorator = A [OK]
Hint: Use @app.before_request decorator above the function [OK]
Common Mistakes:
  • Calling the function instead of decorating
  • Assigning function instead of decorating
  • Missing the @ symbol for decorator
3. Given this Flask code, what will be the output when accessing /?
from flask import Flask, request, abort
app = Flask(__name__)

@app.before_request
def check_auth():
    if request.args.get('token') != 'secret':
        abort(401)

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

# Assume app runs normally
medium
A. Displays 'Welcome!' if URL has ?token=secret, else 401 Unauthorized error
B. Always displays 'Welcome!' regardless of token
C. Always returns 401 Unauthorized error
D. Raises a syntax error due to missing return in before_request

Solution

  1. Step 1: Understand the before_request check

    The check_auth function runs before every request and aborts with 401 if the 'token' query parameter is not 'secret'.
  2. Step 2: Analyze the route behavior

    If the token is correct, the request proceeds to home() which returns 'Welcome!'. Otherwise, the request is stopped early with 401.
  3. Final Answer:

    Displays 'Welcome!' if URL has ?token=secret, else 401 Unauthorized error -> Option A
  4. Quick Check:

    before_request aborts if token wrong = C [OK]
Hint: before_request can block requests early with abort() [OK]
Common Mistakes:
  • Thinking before_request must return a value
  • Assuming route runs even if abort called
  • Confusing query parameters with headers
4. Identify the error in this Flask code using before_request:
from flask import Flask
app = Flask(__name__)

@app.before_request
def setup():
    print('Setup done')

@app.route('/')
def index():
    return 'Hello'
medium
A. Missing parentheses in @app.before_request decorator
B. No return statement in before_request function causes error
C. No error; code works correctly
D. Route function must be named before_request

Solution

  1. Step 1: Check before_request function requirements

    The before_request function can run code and does not need to return anything unless it wants to stop the request.
  2. Step 2: Verify decorator and route correctness

    The decorator syntax is correct, and the route function is properly defined with a return statement.
  3. Final Answer:

    No error; code works correctly -> Option C
  4. Quick Check:

    before_request can have no return = B [OK]
Hint: before_request functions don't need to return unless blocking [OK]
Common Mistakes:
  • Expecting before_request to always return a response
  • Confusing decorator syntax with function call
  • Thinking route function must be named before_request
5. You want to use before_request to check if a user is logged in by verifying a session key. If not logged in, redirect to /login. Which code snippet correctly implements this?
hard
A. from flask import redirect, session def check_login(): if 'user' not in session: return redirect('/login') app.before_request(check_login())
B. from flask import redirect, session @app.before_request def check_login(): if 'user' not in session: return redirect('/login')
C. from flask import redirect, session @app.before_request def check_login(): if session['user'] is None: return redirect('/login')
D. from flask import redirect @app.before_request def check_login(): if session.get('user') == False: return redirect('/login')

Solution

  1. Step 1: Check session key existence safely

    from flask import redirect, session @app.before_request def check_login(): if 'user' not in session: return redirect('/login') uses 'user' not in session which safely checks if the user is logged in.
  2. Step 2: Confirm correct decorator and redirect usage

    from flask import redirect, session @app.before_request def check_login(): if 'user' not in session: return redirect('/login') uses the @app.before_request decorator and returns a redirect response correctly to stop further processing.
  3. Final Answer:

    from flask import redirect, session @app.before_request def check_login(): if 'user' not in session: return redirect('/login') -> Option B
  4. Quick Check:

    Use @app.before_request and check 'user' in session = A [OK]
Hint: Use @app.before_request and check session key presence [OK]
Common Mistakes:
  • Calling the function instead of decorating
  • Checking session key with wrong condition
  • Not returning redirect to stop request
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