Reputation: 1075
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?
Upvotes: 3
Views: 488
Reputation: 5482
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
Upvotes: 1