The login_required decorator makes sure only logged-in users can see certain pages. It helps keep parts of your website private.
Login_required decorator in Flask
@login_required def your_view_function(): # code for the view return something
Place @login_required right above the view function you want to protect.
This decorator is provided by Flask-Login extension, so you need to install and set up Flask-Login first.
dashboard page so only logged-in users can access it.@login_required def dashboard(): return 'Welcome to your dashboard!'
profile route is protected by login_required.@app.route('/profile') @login_required def profile(): return 'User profile page'
This Flask app uses Flask-Login to protect the /protected page. You must visit /login first to log in. Then you can access /protected. The login_required decorator blocks access to /protected and /logout if not logged in.
from flask import Flask, redirect, url_for from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user app = Flask(__name__) app.secret_key = 'secret-key' login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' class User(UserMixin): def __init__(self, id): self.id = id users = {'user1': User('user1')} @login_manager.user_loader def load_user(user_id): return users.get(user_id) @app.route('/login') def login(): user = users['user1'] login_user(user) return 'Logged in! Go to /protected' @app.route('/protected') @login_required def protected(): return f'Hello, {current_user.id}! This page is protected.' @app.route('/logout') @login_required def logout(): logout_user() return 'Logged out!' if __name__ == '__main__': app.run(debug=False)
Remember to set login_manager.login_view to the login route so users get redirected properly.
If a user is not logged in and tries to access a protected page, they will be sent to the login page automatically.
You need to create a user loader function to tell Flask-Login how to find users.
login_required keeps pages safe by allowing only logged-in users.
Use it by placing @login_required above your view functions.
It works with Flask-Login and redirects users to login if they are not authenticated.
Practice
@login_required decorator in Flask?Solution
Step 1: Understand the role of
This decorator is used to protect routes so only authenticated users can access them.@login_requiredStep 2: Identify what it does in Flask-Login
If a user is not logged in, it redirects them to the login page instead of showing the protected content.Final Answer:
To restrict access to a view so only logged-in users can see it -> Option BQuick Check:
Access control = Restrict to logged-in users [OK]
- Confusing login_required with user registration
- Thinking it logs out users automatically
- Assuming it shows messages instead of restricting access
@login_required decorator in a Flask view function?Solution
Step 1: Recall Python decorator syntax
Decorators are placed on the line above the function with an @ symbol, then the function is defined normally.Step 2: Match correct syntax for
@login_required def my_view(): pass correctly places@login_required@login_requiredabove the function definition.Final Answer:
@login_required\ndef my_view(): pass -> Option CQuick Check:
Decorator above function = @login_required def my_view(): pass [OK]
- Placing @login_required inside the function signature
- Trying to use @login_required after function definition
- Using invalid Python syntax for decorators
@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?Solution
Step 1: Understand
This decorator checks if the user is authenticated before allowing access.@login_requiredbehaviorStep 2: What happens if user is not logged in?
The decorator redirects unauthenticated users to the login page automatically.Final Answer:
They are redirected to the login page -> Option AQuick Check:
Not logged in = redirect to login [OK]
- Thinking the page content shows anyway
- Assuming a 404 error occurs
- Believing the server crashes
from flask_login import login_required
@app.route('/profile')
def profile():
return 'User Profile'
Why will this code NOT restrict access to logged-in users?Solution
Step 1: Check if
The function@login_requiredis appliedprofilelacks the@login_requireddecorator above it.Step 2: Understand decorator order and import
Import fromflask_loginis correct, and route decorator order is flexible, but missing@login_requiredmeans no access restriction.Final Answer:
Because @login_required is missing above the profile function -> Option DQuick Check:
Missing decorator = no restriction [OK]
- Thinking import location causes the issue
- Believing decorator order is wrong
- Assuming function name affects access control
@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 neededSolution
Step 1: Understand how to protect multiple routes efficiently
Applying@login_requiredindividually works but is repetitive.Step 2: Use
Flask'sbefore_requestto check login once for all routesbefore_requestruns before every request, so you can check if the user is logged in and redirect if not, protecting multiple routes centrally.Step 3: Evaluate other options
Use a custom decorator that wraps @login_required and apply it to each function still requires decorating each function. Apply @login_required once on the Flask app object is invalid because@login_requiredis 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.Final Answer:
Use Flask's before_request to check login status and redirect if needed -> Option AQuick Check:
Central login check = before_request [OK]
- Thinking one decorator on app protects all routes
- Assuming decorators cascade automatically
- Not knowing about before_request hook
Ready to prove it?
Pass the test and this pattern moves unknown
