SQLAlchemy:session何时commit,何时close?
参考阅读:SQLAlchemy - 官方文档
官方文档说明了关于什么是session,以及如何创建session、如何使用session、如何关闭session
参考阅读 - When do I construct a Session, when do I commit it, and when do I close it?
-
As a general rule, keep the lifecycle of the session separate and external from functions and objects that access and/or manipulate database data. This will greatly help with achieving a predictable and consistent transactional scope.
一般来说,将会话的生命周期与访问和/或操作数据库数据的函数和对象分开。这将极大地帮助实现可预测和一致的事务范围。 -
Make sure you have a clear notion of where transactions begin and end, and keep transactions short, meaning, they end at the series of a sequence of operations, instead of being held open indefinitely.
确保您对事务在何处开始和结束有一个清晰的概念,并保持事务简短,即它们在一系列操作中结束,而不是无限期地保持打开状态。
官方示例
E.g. don’t do this:
### this is the **wrong way to do it** ###
class ThingOne(object):
def go(self):
session = Session()
try:
session.query(FooBar).update({
"x": 5})
session.commit(