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

Avi*_*Raj 7 python sqlalchemy flask-sqlalchemy

在特定表上发生插入后,我正在尝试执行一些操作。

user = ModelFactory.create_user(username, email, password)
db.session.add(user)
db.session.commit()
Run Code Online (Sandbox Code Playgroud)

所以我创建了一个自动调用的方法 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)
Run Code Online (Sandbox Code Playgroud)

但是这段代码显示了一个警告,例如,

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
Run Code Online (Sandbox Code Playgroud)

这篇文章表明我们必须在before_flush. 我尝试在 before_flush 方法中移动逻辑,但它显示 user.id 为 None。是的,这是意料之中的,因为实体不会提交给 db。

同样,我尝试过after_flush事件,但仍然收到相同的警告。

uni*_*rio 7

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"))
Run Code Online (Sandbox Code Playgroud)

但是你为什么不想User.author建立关系呢?