BudiBadu Logo
Samplebadu

Flask by Example: SQLAlchemy Model Mapping

Flask 3.0+

Flask-SQLAlchemy is an extension that simplifies using SQLAlchemy with Flask. Models map Python classes to database tables, allowing you to work with objects instead of raw SQL.

Code

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

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

# Define a Model
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'

# Usage (usually in a view or shell):
# with app.app_context():
#     db.create_all()  # Create tables
#     
#     admin = User(username='admin', email='[email protected]')
#     db.session.add(admin)
#     db.session.commit()
#     
#     users = User.query.all()

Explanation

Flask-SQLAlchemy abstracts the database interactions, allowing you to define your database schema using Python classes called Models. Each attribute in the class represents a table column, with SQLAlchemy handling the translation between Python types and SQL types.

The db.session object is your interface for managing transactions. You add objects to the session and then call commit() to save all changes to the database in a single transaction.

This ensures data integrity through the Unit of Work pattern. If an error occurs before the commit, you can roll back the session to leave the database in a consistent state.

Code Breakdown

5
SQLALCHEMY_DATABASE_URI tells SQLAlchemy where to connect. SQLite is great for development; PostgreSQL or MySQL are used in production.
9
class User(db.Model) inherits from a base class that provides all the ORM magic (querying, saving, etc.).
10
db.Column defines the schema. primary_key=True is essential for identifying records. unique=True enforces a database constraint.