Overview

Flask-SQLAlchemy 3.0, released on January 6, 2023, adds SQLAlchemy 2.0 support and rewrites session management.

Main Features

SQLAlchemy 2.0 support

The extension supports SQLAlchemy 2.0's new declarative style with mapped_column() and DeclarativeBase, while remaining compatible with the old style.

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
    pass

db = SQLAlchemy(model_class=Base)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db.init_app(app)

class Article(db.Model):
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(db.String(200))

Session rewrite

Session management has been completely rewritten to better integrate with the Flask request lifecycle. The session is automatically closed at the end of each request.

python
from flask import Flask

@app.route('/articles')
def list_articles():
    # Session is managed automatically
    articles = db.session.execute(
        db.select(Article).order_by(Article.title)
    ).scalars().all()
    return [{'id': a.id, 'title': a.title} for a in articles]

# db.session is closed at the end of the request
# No need for explicit db.session.remove()

Sources