【问题标题】:SAWarning: Usage of the 'Session.add()' operation is not currently supported within the execution stageSAWarning:执行阶段当前不支持使用“Session.add()”操作
【发布时间】: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


    【解决方案1】:

    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 建立关系呢?

    【讨论】:

    • 在通知用户方法的开始,我添加了db.session.flush(),它可以工作
    • @AvinashRaj 我觉得你没有充分利用 ORM。 ORM 的一个主要特性是能够确定插入对象的顺序,以便能够填写外键。
    • 你的意思是db.sessionSession 一样吗?
    • @AvinashRaj 他们应该都可以工作,尽管db.session 可能更正确。
    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多