Performance: Login_required decorator
This affects the server response time and user experience by adding authentication checks before rendering protected pages.
from flask import Flask from flask_login import LoginManager, login_required app = Flask(__name__) login_manager = LoginManager(app) @app.route('/dashboard') @login_required def dashboard(): return 'Welcome to your dashboard!'
from flask import Flask, redirect, url_for, session app = Flask(__name__) @app.route('/dashboard') def dashboard(): if 'user' not in session: return redirect(url_for('login')) return 'Welcome to your dashboard!'
| Pattern | Server Processing | Code Duplication | Response Delay | Verdict |
|---|---|---|---|---|
| Manual login check in each route | High - repeated checks | High - duplicated code | Medium - multiple checks add delay | [X] Bad |
| Using login_required decorator | Low - centralized check | Low - single reusable decorator | Low - single quick check | [OK] Good |
@login_required decorator in Flask?@login_required@login_required decorator in a Flask view function?@login_required@login_required above the function definition.@login_required:
@app.route('/dashboard')
@login_required
def dashboard():
return 'Welcome to your dashboard'
What happens if a user who is NOT logged in tries to visit /dashboard?@login_required behaviorfrom flask_login import login_required
@app.route('/profile')
def profile():
return 'User Profile'
Why will this code NOT restrict access to logged-in users?@login_required is appliedprofile lacks the @login_required decorator above it.flask_login is correct, and route decorator order is flexible, but missing @login_required means no access restriction.@login_required decorator on each function?
A) Use a custom decorator that wraps @login_required and apply it to each function
B) Apply @login_required once on the Flask app object
C) Add @login_required only to the first route function and it applies to all others
D) Use Flask's before_request to check login status and redirect if needed@login_required individually works but is repetitive.before_request to check login once for all routesbefore_request runs before every request, so you can check if the user is logged in and redirect if not, protecting multiple routes centrally.@login_required is not applied to the app object. Add @login_required only to the first route function and it applies to all others is incorrect because decorators do not cascade to other functions.Pass the test and this pattern moves unknown