简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM