DEV Community

Cover image for SQLAlchemy Events
Ngalim Siregar
Ngalim Siregar

Posted on

SQLAlchemy Events

During the normal operation in SQLAlchemy ORM objects may be created, updated, and destroyed. SQLAlchemy provides hooks into this object life cycle so that you can control your application and its data.

These callbacks allow you to trigger logic before or after an alteration of an object's state.

Here is a sample of Flask-SQLAlchemy 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
Enter fullscreen mode Exit fullscreen mode

If we want to add callback to lowercase username before save, we can use sqlalchemy.event.listens_for

from sqlalchemy import event


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


@event.listens_for(User, "before_insert")
def lowercase(mapper, connection, target):
    target.username = target.username.lower()
Enter fullscreen mode Exit fullscreen mode

By using sqlalchemy-events library, we can simplify those event listen to

from sqlalchemy_events import listen_events, on


@listen_events
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)

    @on("before_insert")
    def lowercase_username(mapper, conn, self):
        self.username = self.username.lower()

    def __repr__(self):
        return '<User %r>' % self.username
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
_mikeusa profile image
Mike

This is good, concise information. Is there a pattern to provide listeners for mixin classes?