【问题标题】:Commit despite raising custom exception in SQLAlchemy尽管在 SQLAlchemy 中引发自定义异常,但仍提交
【发布时间】:2021-09-09 03:11:15
【问题描述】:

每当有新记录插入表时,我都会尝试显示警报。为了传达新数据已插入,我提出了一个自定义异常。但是,我发现只要引发自定义异常,提交就不会成功完成。尽管有异常,是否可以强制它完成,或者有更好的替代方法吗?

@event.listens_for(Session, "after_flush")
def after_flush(session, flush_context):
    for instance in session.new:
        if hasattr(instance, "on_insert"):
            instance.on_insert(session)

如果我不引发自定义异常,则以下提交正常

    def on_insert(self, session):
        # Removed code which utilises the passed in session, as such after_insert event hook is probably not going to be suitable
        session.commit() # Leads to ResourceClosedError which rolls back the transaction
        raise NewClientError(f"{self.__repr__()}")
        #pass

由于上面的 on_insert 是在父事务中运行的,再次执行 commit() 最终会导致 ResourceClosedError 回滚父事务。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    我已经通过引发自定义异常作为 after_commit 事件挂钩的一部分来解决这个问题:

    https://gist.github.com/letmaik/b296b02e730cd4c469bfHow do I get SQLAlchemy objects after commit?

    在我的例子中,我刚刚修改了 on_insert 函数来为 after_commit 注册一个监听器:

        def on_insert(self, session):
            event.listen(session, "after_commit", self.__raise_alert)
    

    现在在事务完成后调用 __raise_alert,因此不会导致回滚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-26
      • 2017-04-17
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多