Bird
0
0

Given this Flask code, what will be the output when accessing /?

medium📝 component behavior Q13 of 15
Flask - Middleware and Extensions
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
ADisplays 'Welcome!' if URL has ?token=secret, else 401 Unauthorized error
BAlways displays 'Welcome!' regardless of token
CAlways returns 401 Unauthorized error
DRaises a syntax error due to missing return in before_request
Step-by-Step Solution
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]
Quick Trick: before_request can block requests early with abort() [OK]
Common Mistakes:
MISTAKES
  • Thinking before_request must return a value
  • Assuming route runs even if abort called
  • Confusing query parameters with headers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes