SAWarning:使用' Session.add()'执行阶段当前不支持操作

时间:2017-04-02 04:09:57

标签: python sqlalchemy flask-sqlalchemy

我尝试在特定表上插入后执行某些操作。

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事件,但我仍然收到同样的警告。

1 个答案:

答案 0 :(得分:2)

after_flush事件确实有效:

@event.listens_for(User, "after_insert")
def receive_after_insert(mapper, connection, user):
    print(user.id)
    @event.listens_for(Session, "after_flush", once=True)
    def receive_after_flush(session, context):
        session.add(Book(author=user.id, name="foo"))

但为什么你不想让User.author成为一个关系呢?