session = get_the_session_one_way_or_another()
try:
# do something with the session
except: # * see comment below
session.rollback()
raise
else:
session.commit()
为了使事情更易于使用,将其作为上下文管理器很有用:
^{pr2}$
然后:
with get_session() as session:
# do something with the session
我在使用sqlalchemy时通常会有这种模式:
为了使事情更易于使用,将其作为上下文管理器很有用:
^{pr2}$然后:
如果在块中引发异常,则上下文管理器将回滚事务。在
*有一个空的
except:
它可以捕捉所有的东西。这通常不是您想要的,但是在这里总是会重新引发异常,所以没关系。相关问题 更多 >
编程相关推荐