DEV Community

Cover image for SQLAlchemy Events
Ngalim Siregar
Ngalim Siregar

Posted on

4 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
_mikeusa profile image
Mike

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay