【发布时间】: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