@login_required. What is the typical behavior if a user tries to access this route without being logged in?from flask import Flask, redirect, url_for from flask_login import LoginManager, login_required app = Flask(__name__) login_manager = LoginManager(app) @login_manager.unauthorized_handler def unauthorized(): return redirect(url_for('login')) @app.route('/dashboard') @login_required def dashboard(): return 'Welcome to your dashboard!' @app.route('/login') def login(): return 'Please log in.'
unauthorized_handler does in Flask-Login.The @login_required decorator checks if the user is logged in. If not, Flask-Login calls the unauthorized_handler, which usually redirects the user to the login page.
@login_required decorator?The @login_required decorator must be placed directly above the route function, after the @app.route decorator. Option B shows the correct order.
@login_required, what will current_user.is_authenticated return?from flask_login import current_user, login_required @app.route('/settings') @login_required def settings(): return str(current_user.is_authenticated)
The @login_required decorator ensures the user is logged in before running the route. Therefore, current_user.is_authenticated will always be True inside that route.
/profile cause a redirect loop?from flask import Flask, redirect, url_for from flask_login import LoginManager, login_required app = Flask(__name__) login_manager = LoginManager(app) @login_manager.unauthorized_handler def unauthorized(): return redirect(url_for('profile')) @app.route('/profile') @login_required def profile(): return 'User Profile'
The unauthorized handler redirects to /profile, which is protected by @login_required. Since the user is not logged in, this causes a redirect loop.
@login_required decorator works within Flask's request handling process?The @login_required decorator wraps the route function. It checks if the user is authenticated before the route runs. If not, it redirects the user, preventing the route function from executing.