【发布时间】:2017-04-04 03:11:32
【问题描述】:
我正在尝试在特定表上发生插入后执行一些操作。
user = ModelFactory.create_user(username, email, password)
db.session.add(user)
db.session.commit()
所以我创建了一个在after_insert 上自动调用的方法。
def notify_user(user):
print user.id
book = Book(author=user.id, name='foo')
db.session.add(book)
db.session.commit(book)
@event.listens_for(User, 'after_insert')
def receive_after_insert(mapper, connection, target):
print target
notify_user(target)
但是这段代码显示了类似的警告,
SAWarning: Usage of the 'Session.add()' operation is not currently supported within the execution stage of the flush process. Results may not be consistent. Consider using alternative event listeners or connection-level operations instead.
% method)
/home/avinash/.virtualenvs/s2s/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py:68: SAWarning: An exception has occurred during handling of a previous exception. The previous exception is:
<class 'sqlalchemy.exc.ResourceClosedError'> This transaction is closed
This 帖子显示我们必须在before_flush 中完成工作。我尝试在 before_flush 方法中移动逻辑,但它显示 user.id 为 None。是的,这是意料之中的,因为实体不会被提交给 db。
同样,我尝试了after_flush 事件,但仍然收到相同的警告。
【问题讨论】:
标签: python sqlalchemy flask-sqlalchemy