我很好奇是否有办法显示当前 session 中的内容?
或者也许是一种检查 session 是否为空的方法,以便我可以执行如下所示的操作。
if db.session:
db.session.commit()
这样它只会在 session 中确实有东西等待提交时才提交。
最佳答案
有以下属性可以检查 session 状态:
-
Session.new
- 对于将添加到数据库的对象。 -
Session.dirty
- 对于将要更新的对象。 -
Session.deleted
- 对于将从数据库中删除的对象。
这三个属性可用于检查 session 状态:
if not db.session.new and not db.session.dirty and not db.session.deleted:
# do smth
然而,即使 session 没有变化,调用 session.commit()
也是安全的。如果您不做一些特别的事情,则不需要在提交之前显式检查 session 状态。
还有一个名为Session._is_clean()
的私有(private)方法,用于检查是否有任何更改要刷新到数据库。它是这样实现的:
def _is_clean(self):
return not self.identity_map.check_modified() and \
not self._deleted and \
not self._new
关于python - SQLAlchemy - 有没有办法查看当前 session 中的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31928520/