SQLAlchemy-有没有办法查看会话中当前的内容? [英] SQLAlchemy - Is there a way to see what is currently in the session?
问题描述
我很好奇是否有一种方法可以显示会话中当前的内容吗?
I'm curious if there's a way to show what is currently in the session?
或者是一种检查会话是否为空的方法,以便我可以执行以下操作.
Or perhaps a way to check if the session is empty or not so that I can do something like the below.
if db.session:
db.session.commit()
这样,仅当会话中确实有某些内容等待提交时,才会提交.
This way it will only commit if there's actually something in the session waiting to be committed.
推荐答案
有以下属性可用于检查会话状态:
There are following properties to check session state:
-
Session.new
-用于对象,它将添加到数据库中. -
Session.dirty
-用于将要更新的对象. -
Session.deleted
-用于对象,该对象将从数据库中删除.
这三个属性可用于检查会话状态:
These three properties can be used to check session state:
if not db.session.new and not db.session.dirty and not db.session.deleted:
# do smth
但是,即使会话没有变化,也可以安全地调用 session.commit()
.如果您没有做任何特别的事情,则无需在提交之前显式检查会话状态.
However it is safe to call session.commit()
even if there is no changes in session. If you don't do something special, you don't need to explicitly check session state before commit.
还有一个名为 Session._is_clean()
的私有方法,该方法用于检查是否有任何要刷新到数据库的更改.它是这样实现的:
Also there is a private method called Session._is_clean()
, which is used to check if there are any changes to be flushed to database. It's implemented like this:
def _is_clean(self):
return not self.identity_map.check_modified() and \
not self._deleted and \
not self._new
这篇关于SQLAlchemy-有没有办法查看会话中当前的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!