from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin app = Flask(__name__) app.config['SECRET_KEY'] = 'mysecretkey' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True) password = db.Column(db.String(60)) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) login_manager.anonymous_user = User(id=-1, username='Guest')
from flask import render_template from flask_login import login_required @app.route('/dashboard') @login_required def dashboard(): return render_template('dashboard.html')In this example, the `dashboard` view function is decorated with `@login_required`, which will redirect the user to the login page if they are not authenticated. Otherwise, the view function will render the `dashboard.html` template. Overall, `flask.ext.login` is a useful package library for managing user authentication and login sessions in a Flask application.