In Flask, if a before_request function returns a response, what is the effect on the request processing?
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 '/'?
Think about how Flask handles returned responses in before_request functions.
If a before_request function returns a response, Flask stops processing further handlers and sends that response immediately.
Which of the following code snippets correctly registers a before_request function in Flask?
Remember the decorator syntax for Flask hooks.
The before_request decorator is used without parentheses to register a function.
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?
Check the return type of the before_request function when blocking access.
Returning a plain string and status code tuple is valid in Flask, so option A is correct behavior. But if the function returns None or does not return anything, Flask continues processing. If the function returns a non-response type that Flask can't handle, it raises an error. The question states unauthorized access is not blocked, so the function likely returns None or does not return the response properly.
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 '/'?
Think about how Flask's g object works across requests.
The before_request function sets g.user before the route runs. The route accesses g.user and returns 'Hello, Alice!'.
Which statement best describes the difference between Flask's before_request functions and middleware in frameworks like Express.js or Django?
Consider how control flow works in Flask before_request vs middleware chains.
Flask's before_request functions run before each request but do not support chaining or calling next middleware explicitly. Middleware in Express.js or Django often form chains where each middleware calls next() to continue.