How to disable caching in an Sqlalchemy ORM session?

I have a thread in daemons that executes a loop and executes the following request:

    try:
        newsletter = self.session.query(models.Newsletter).\
               filter(models.Newsletter.status == 'PROCESSING').\
               limit(1).one()
    except sa.orm.exc.NoResultFound:
        self.logger.debug('No PROCESSING newsletters found. Sleeping...')
        self.sleep()
        return
    # (...) more code to do with found newsletter

If the sleep method simply stops executing this thread for the configured time, and the return statement returns to the main loop. However, I found that if I change the status of the newsletter to “PROCESSING” while the daemon is running, nothing happens, i.e. the request still calls NoResultFound. However, if I restart the daemon, it will find the newsletter. Therefore, I see that the results of this query should be cached. What can I do to invalidate the cache? session.expire_all () does not work. I could also create a new Session () object at each iteration, but I don't know if this applies well to system resources.

+4
source share
4 answers

SQLAlchemy does not cache by itself. Unless you have explicitly implemented a cache like this .

Go echo=Trueto yours sessionmakerand see the loggingoutput .

+5
source

The problem in your code is with the database using the REPEATABLE READ isolation level by default, so the query returns the same result if you do not call commit()either rollback()(or use autocommit=Trueas suggested by Xeross) or manually change the isolation level.

, SQLAlchemy ( !), ORM . SQLAlchemy , , . , , .

+3

, , session.commit(), , autocommit = True , , sessionmaker.

sessionmaker(bind=self.engine, autocommit=True)

session.commit()

, , , .

+1

autocommit = True expire_on_commit = True

for state in self.identity_map.all_states():
    state.expire(state.dict, self.identity_map._modified)

you can: after request: db.session.commit ()

+1
source

All Articles