What if you could write a login check once and have it work everywhere automatically?
Why Before_request hooks in Flask? - Purpose & Use Cases
Imagine you have a web app where every page needs to check if a user is logged in before showing content.
You write this check on every single page route manually.
Manually adding login checks to every route is repetitive and easy to forget.
This leads to security holes or inconsistent behavior across pages.
Before_request hooks let you run code automatically before every request.
This means you write your login check once, and it applies everywhere.
def page(): if not logged_in(): return redirect('/login') return 'Page content'
@app.before_request def check_login(): if not logged_in(): return redirect('/login')
You can centralize common checks or setup steps, making your app safer and easier to maintain.
Many websites require users to be logged in to access their dashboard.
Using before_request hooks, the login check runs automatically before showing any dashboard page.
Manually repeating code for every route is error-prone.
Before_request hooks run code before all requests automatically.
This keeps your app consistent, secure, and easier to update.
Practice
before_request hook in Flask?Solution
Step 1: Understand the role of
Thebefore_requestbefore_requesthook runs before each request to prepare data or check conditions.Step 2: Compare with other options
Defining routes, handling errors, or sending responses happen elsewhere, not inbefore_request.Final Answer:
To run code before every request to prepare or check something -> Option AQuick Check:
before_request runs before request = C [OK]
- Confusing before_request with route handlers
- Thinking it handles errors or sends responses
- Assuming it runs after the request
before_request hook in Flask that does not short-circuit the request?Solution
Step 1: Recall the decorator syntax
Thebefore_requestdecorator is used without parentheses:@app.before_request.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.Final Answer:
@app.before_request\ndef before(): pass -> Option DQuick Check:
Decorator without () and function = D [OK]
- Adding parentheses after @app.before_request
- Defining a class instead of a function
- Returning a value when not needed
/?
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'Solution
Step 1: Analyze the before_request hook
Thecheckfunction unconditionally returns a redirect to/loginfor every request.Step 2: Determine the final response
Request to/redirects to/login, but/loginalso triggersbefore_requestwhich redirects again, causing an infinite loop.Final Answer:
Redirect loop error -> Option CQuick Check:
Always redirect to /login = C [OK]
- Expecting 'Login Page' without considering loop
- Thinking before_request does not run on /login
- Ignoring that every request triggers the hook
from flask import Flask
app = Flask(__name__)
@app.before_request
def before():
print('Before request')
return None
@app.route('/')
def index():
return 'Hello'Solution
Step 1: Understand return behavior in before_request
Returning None means no response is sent, so Flask continues to route handler.Step 2: Check if printing is allowed
Printing is allowed and useful for debugging; it does not cause errors.Final Answer:
Nothing is wrong; code works fine -> Option BQuick Check:
None return means continue normal route = A [OK]
- Thinking return None causes error
- Believing before_request must always return response
- Assuming print statements break Flask hooks
before_request hook to block access to all routes except /login unless a user is logged in. Which code snippet correctly implements this?Solution
Step 1: Identify the condition to block access
We want to redirect to/loginif the path is not/loginand user is not logged in.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.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 AQuick Check:
Check path and session, redirect if not logged in = A [OK]
- Redirecting /login to itself causing loop
- Not checking path before redirect
- Returning string instead of redirect response
Ready to prove it?
Pass the test and this pattern moves unknown
