Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Sqlalchemy-异常时回滚_Python_Sqlalchemy - Fatal编程技术网

Python Sqlalchemy-异常时回滚

Python Sqlalchemy-异常时回滚,python,sqlalchemy,Python,Sqlalchemy,我需要在core.event'handle\u error'(catch'KeyboardInterrupt')中回滚事务,但此事件中的参数是ExceptionContext,如何执行此操作?在使用sqlalchemy时,我通常有这种模式: session = get_the_session_one_way_or_another() try: # do something with the session except: # * see commen

我需要在
core.event'handle\u error'(catch'KeyboardInterrupt')
中回滚事务,但此事件中的参数是
ExceptionContext
,如何执行此操作?

在使用sqlalchemy时,我通常有这种模式:

session = get_the_session_one_way_or_another()

try:
    # do something with the session
except:                   # * see comment below
    session.rollback()
    raise
else:
    session.commit()
为了使事情更易于使用,将其用作上下文管理器非常有用:

@contextmanager
def get_session():
    session = get_the_session_one_way_or_another()

    try:
        yield session
    except:
        session.rollback()
        raise
    else:
        session.commit()
然后:

with get_session() as session:
    # do something with the session
如果在块内引发异常,则上下文管理器将回滚事务



*除了:之外,还有一个空的
,它可以捕获所有内容。这通常不是您想要的,但是这里总是会重新引发异常,所以这很好。

感谢您的响应,但我需要在handler\u error core.event中处理异常signal@SmartElectron好的,但我很好奇,你能解释一下为什么需要这种方法吗?如果我们在
session.commit()中遇到异常怎么办
当我们不重新引发异常时?@Pranjal在
session.commit()中的异常未被捕获,因为它在
try
块之外,所以不需要重新引发它。@zvone这就是为什么,我认为更好的方法是包含
session.commit()
中尝试
块本身,而不是在else块中。