Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy event registration

I'm trying to figure out how SQLAlchemy handles event registration. I have a situation where I want to keep all of my event listeners in a single file, rather than in the model (I want to do this to avoid my models importing controllers with business logic). But if I try to do something like the following in a separate file the code will not fire:

from sqlalchemy.event import listens_for
from models import User


@listens_for(User, 'before_update')
def before_update_listener(mapper, connection, instance):
    print "do something"

Which makes sense, this module is never imported, but then how do I tell SQLAlchemy that event listeners exist in some listeners.py file?

like image 407
NFicano Avatar asked Feb 15 '26 11:02

NFicano


1 Answers

The file must be imported, you can do something like the following:

# listeners.py
from sqlalchemy.event import listens_for
from models import User


@listens_for(User, 'before_update')
def before_update_listener(mapper, connection, instance):
    print "do something"

.

# __init__.py
from . import events
del events
like image 154
RazerM Avatar answered Feb 16 '26 23:02

RazerM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!