Flask-SQLAlchemy

Flask-SQLAlchemy is the extension that integrates the SQLAlchemy ORM into Flask. It manages the database connection and session for you and lets you define tables as Python classes (models) with db.Model.

Flask

SQLAlchemy is a powerful but generic database toolkit; Flask-SQLAlchemy wraps it so it fits Flask's request lifecycle. You create a db = SQLAlchemy() object, configure SQLALCHEMY_DATABASE_URI, and then subclass db.Model to define tables.

It scopes the database session to each request automatically, so you don't manually open and close connections. After defining models you call db.create_all() to build the tables, and you query through Model.query or the newer db.session.execute(select(...)) API.

Common companions are Flask-Migrate (for schema migrations via Alembic) and Marshmallow (for serializing model objects to JSON in APIs).

Syntax

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

Examples

Python

from flask_sqlalchemy import SQLAlchemy

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

with app.app_context():
    db.create_all()

Learn it in a lesson

See also

Back to the Dictionary