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

原文链接:SQLAlchemy Events

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容