Flask - SQLAlchemy is an extension that simplifies the use of SQLAlchemy, a powerful SQL toolkit and Object - Relational Mapping (ORM) library in Python, within a Flask application. It provides a high - level, Pythonic way to interact with databases, allowing you to define database models as Python classes and perform database operations without writing raw SQL queries.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# Initialize Flask app
app = Flask(__name__)
# Configure the database URI
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///test.db'
# Initialize SQLAlchemy
db = SQLAlchemy(app)
# Define a database model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
# Create all database tables
@app.before_first_request
def create_tables():
db.create_all()
@app.route('/')
def index():
# Create a new user
new_user = User(username='testuser')
db.session.add(new_user)
db.session.commit()
return 'User added!'
if __name__ == '__main__':
app.run(debug=True)
sqlite:///
, mysql+pymysql://
).db.session.commit()
after adding or modifying data.Flask - Login provides user session management for Flask applications. It handles the common tasks of logging in, logging out, and remembering users’ sessions. It integrates well with Flask - SQLAlchemy to manage user authentication.
from flask import Flask, render_template, redirect, url_for, request
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///users.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# User model
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username, password=password).first()
if user:
login_user(user)
return redirect(url_for('protected'))
else:
return 'Invalid credentials'
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/protected')
@login_required
def protected():
return 'This is a protected page!'
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
SECRET_KEY
can lead to issues with session management, such as users being unable to log in or sessions being lost.user_loader
callback function must be defined correctly to load users from the database. If it returns None
for a valid user ID, the user will not be able to log in.bcrypt
to store user passwords instead of plain text.@login_required
Decorator: Protect your sensitive routes with the @login_required
decorator to ensure that only authenticated users can access them.Flask - Caching is an extension that allows you to cache the results of view functions in your Flask application. Caching can significantly improve the performance of your application by reducing the number of expensive operations, such as database queries or API calls.
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
# Configure caching
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@cache.cached(timeout=300)
@app.route('/')
def index():
# Simulate an expensive operation
import time
time.sleep(5)
return 'This page is cached for 5 minutes!'
if __name__ == '__main__':
app.run(debug=True)
simple
cache in a production environment) can result in poor performance or limited caching capabilities.Flask - RESTful is an extension for Flask that simplifies the creation of RESTful APIs. It provides a set of classes and decorators to define API resources and handle HTTP requests.
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
In 2025, these Flask extensions - Flask - SQLAlchemy, Flask - Login, Flask - Caching, and Flask - RESTful - continue to be essential tools for Flask developers. They provide powerful features that can enhance the functionality, security, performance, and maintainability of your web applications. By understanding their core concepts, typical usage scenarios, common pitfalls, and best practices, you can effectively apply these extensions in real - world projects and build high - quality Flask applications.