【问题标题】:SQLAlchemy - Is there a way to see what is currently in the session?SQLAlchemy - 有没有办法查看当前会话中的内容?
【发布时间】:2015-11-02 21:31:00
【问题描述】:
我很好奇是否有一种方法可以显示当前会话中的内容?
或者也许是一种检查会话是否为空的方法,以便我可以执行以下操作。
if db.session:
db.session.commit()
这样,只有在会话中确实有某些内容等待提交时,它才会提交。
【问题讨论】:
标签:
python
session
flask
sqlalchemy
【解决方案1】:
有以下属性可以检查会话状态:
这三个属性可用于检查会话状态:
if not db.session.new and not db.session.dirty and not db.session.deleted:
# do smth
但是,即使会话没有变化,调用session.commit() 也是安全的。如果你不做一些特别的事情,你不需要在提交之前显式检查会话状态。
还有一个名为Session._is_clean() 的私有方法,用于检查是否有任何更改要刷新到数据库。它是这样实现的:
def _is_clean(self):
return not self.identity_map.check_modified() and \
not self._deleted and \
not self._new
【讨论】:
-
您可以使用is_modified,但您确实最好只提交并依靠 SQLAlchemy 来做最优化的事情。无论如何,感谢指向新/脏/已删除的指针。正是我想要的。