How to disable caching correctly in Sqlalchemy orm session?

前端 未结 4 465
执笔经年
执笔经年 2021-01-19 12:48

I have I thread in a daemon, that loops and performs the following query:

    try:
        newsletter = self.session.query(models.Newsletter).\\
                     


        
相关标签:
4条回答
  • 2021-01-19 13:13

    SQLAlchemy doesn't cache on itself. Unless you explicitly implemented a cache, like this one.

    Pass echo=True to your sessionmaker and look into the logging output.

    0 讨论(0)
  • 2021-01-19 13:31

    The problem in your code is due to database using REPEATABLE READ isolation level by default, so the query returns the same result unless you call commit() or rollback() (or use autocommit=True as Xeross suggested) or manually change isolation level.

    Yes, SQLAlchemy does cache mapped objects (not query results!), because ORM pattern requires single object for each identity. By default SQLAlchemy uses weak identity map as cache, so object is automatically expunged from session when there is no references left to it. Note, that subsequent queries will update state of cached objects with new data, so no need to worry about this cache.

    0 讨论(0)
  • 2021-01-19 13:31

    Hmm I already found the answer, you apparently need to explicitly do session.commit() to get it to update, or you need to set autocommit=True on the session, through for example the sessionmaker.

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

    However I haven't tested the session.commit() way

    So this isn't a caching issue it seems to be just the way transactions work

    0 讨论(0)
  • 2021-01-19 13:39

    don't use autocommit=True and expire_on_commit=True

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

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

    0 讨论(0)
提交回复
热议问题