Bird
Raised Fist0
Flaskframework~10 mins

Before_request hooks in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Before_request hooks
Client sends HTTP request
↓
Flask receives request
↓
Run before_request hooks
↓
Hook 1
↓
If hook returns response?
Yes→Send that response back
No↓
Run view function
↓
Send view response back
When Flask gets a request, it runs all before_request hooks first. If any hook returns a response, Flask sends it immediately. Otherwise, it runs the main view function.
Execution Sample
Flask
from flask import Flask, request
app = Flask(__name__)

@app.before_request
def check_auth():
    if not request.headers.get('Auth'):
        return 'Unauthorized', 401
This code runs check_auth before every request. If 'Auth' header is missing, it stops and returns 401.
Execution Table
StepActionRequest HeadersHook check_auth resultNext StepResponse Sent
1Receive request{'Auth': 'token123'}NoneRun before_request hookNo
2Run before_request hook{'Auth': 'token123'}NoneRun view functionNo
3Run view function{'Auth': 'token123'}NoneSend view responseNo
4Send response{'Auth': 'token123'}NoneDoneYes (view response)
5Receive request{} (no Auth)Returns ('Unauthorized', 401)Send hook responseYes (401 Unauthorized)
💡 Execution stops early if before_request hook returns a response; otherwise, view function runs.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
request.headers{}{'Auth': 'token123'}{'Auth': 'token123'}{'Auth': 'token123'}{'Auth': 'token123'}
hook_resultNoneNoneNoneNoneNone
response_sentNoNoNoYes (view response)Yes (view response)
Key Moments - 2 Insights
Why does Flask stop running the view function when a before_request hook returns a response?
Because the before_request hook returned a response (see execution_table step 5), Flask sends that response immediately and skips the view function.
What happens if no before_request hook returns a response?
Flask continues to run the view function normally (see execution_table steps 1-4), then sends the view's response.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the hook_result at step 2 when 'Auth' header is present?
AError
B'Unauthorized', 401
CNone
DView function response
💡 Hint
Check the 'Hook check_auth result' column at step 2 in execution_table.
At which step does Flask send the response immediately due to a before_request hook?
AStep 3
BStep 5
CStep 1
DStep 4
💡 Hint
Look for the step where 'Response Sent' is 'Yes (401 Unauthorized)' in execution_table.
If the before_request hook never returns a response, what changes in the execution_table?
AView function runs and response is sent at step 4
BFlask skips the view function
CHook result shows a response
DResponse is sent at step 5
💡 Hint
Refer to the normal flow rows where hook_result is None and view function runs.
Concept Snapshot
Flask before_request hooks run before each request.
If a hook returns a response, Flask sends it immediately.
Otherwise, Flask runs the view function.
Use @app.before_request decorator.
Common for auth checks or setup.
Stops request early if needed.
Full Transcript
In Flask, before_request hooks run before the main view function for every incoming request. If any hook returns a response, Flask immediately sends that response and skips the view function. Otherwise, the view function runs normally and its response is sent. This lets you run checks or setup code before handling requests. For example, you can check if an authorization header exists and return a 401 error early if missing. The execution table shows how Flask processes requests step-by-step, running hooks first, then the view, and sending the response. If a hook returns a response, Flask stops early and sends it. This helps control request flow simply and clearly.

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