简体   繁体   中英

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:

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

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.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM