SQLAlchemy Events

nsiregar

Ngalim Siregar

Posted on August 17, 2021

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
💖 💪 🙅 🚩
nsiregar
Ngalim Siregar

Posted on August 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

SQLAlchemy Events
python SQLAlchemy Events

August 17, 2021