Freewind
Freewind

Reputation: 198398

How to add event callbacks to sqlalchemy models?

There is a page demonstrates how to do it when using Elixir:

http://beachcoder.wordpress.com/2007/05/02/adding-event-callbacks-to-sqlalchemyelixir-classes/

But I don't use Elixir, I just use sqlalchemy directly, and define my models as:

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    ...

    def send_email(self):
        # send email to the user

And what I want to do is:

class User(Base):
    __tablename__ = "users"
    ...
    before_insert('init_user', 'send_email')
    before_delete('something_before_delete')

    def init_user(self):
        # init some data of the user
    def send_email(self):
        # send email to the user
    def something_before_delete(self):
        # something before delete

Note the before_insert and before_delete methods. What should I do?

Upvotes: 3

Views: 4005

Answers (1)

avdd
avdd

Reputation: 317

The answer to your question is to use an extension (MapperExtension, SessionExtension...) as described here.

But you almost certainly don't want to do anything like sending an email in such a hook. The right way would be to log the action and post-process the log entry after the transaction has completed.

[EDIT] The sqlalchemy docs have changed; the new way of handling this is to use ORM Events

Upvotes: 5

Related Questions