2016-12-04 98 views
1

我是SQLAlchemy的新手,并且因为它的易用性和事件机制而跳入其中。我找了一些数据插入后执行的方法,但我一直运行到该类型的多个错误“属性[...]”涉及到我指的是SQLAlchemy:不能让event.listens.for()工作

from sqlalchemy import create_engine 
from sqlalchemy.orm import sessionmaker 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy import Column, ForeignKey 
from sqlalchemy import Integer, UnicodeText 
from sqlalchemy import event 

#variables feching is hidden 
db = create_engine("mysql://"+dbLogin+":"+dbPassword+"@"+dbAddress+"/"+dbDatabase) 
metadata = MetaData(db) 
#the log table is not explicitly defined but rather uses the autoload function 
logtable = Table('logs', metadata, autoload=True) 

#and here I am trying to start "processLogChanged" after_insert on the "logs" table 
@event.listens_for(logtable, "after_insert") 
def processLogChanged(): 
    print "---- the log table has changed" 

我明明做的事情的对象错了,但我一直在淘经历了很多问题/答案并不能在这里找到合适的,这将是巨大的,如果你能给我一只手

这里是堆栈例如在这种情况下,

Traceback (most recent call last): 
    File "optra.py", line 144, in <module>@event.listens_for(logtable, "after_insert") 
    File "/home/jpp/anaconda2/lib/python2.7/site-packages/sqlalchemy/event/api.py", line 124, in decorate 
    listen(target, identifier, fn, *args, **kw) 
    File "/home/jpp/anaconda2/lib/python2.7/site-packages/sqlalchemy/event/api.py", line 89, in listen 
    _event_key(target, identifier, fn).listen(*args, **kw) 
    File "/home/jpp/anaconda2/lib/python2.7/site-packages/sqlalchemy/event/registry.py", line 194, in listen 
    dispatch_collection = getattr(target.dispatch, identifier) 
    File "/home/jpp/anaconda2/lib/python2.7/site-packages/sqlalchemy/event/base.py", line 95, in __getattr__ 
    raise AttributeError(name) 
AttributeError: after_insert 

谢谢

回答

0

after_insert事件假定您正在使用由sqlalchemy.ext.declarative.declarative_base声明的表。并且您需要指定事件处理程序的参数mapper,connection,target

Base = declarative_base(metadata) 

class LogTable(Base): 
    __tablename__ = 'logs' 

    id = Column(Integer) 
    # Some other columns 

@event.listens_for(LogTable, 'after_insert') 
def processLogChanged(mapper, connection, target): 
    print "---- the log table has changed"