How does SQLAlchemy track database changes? How does SQLAlchemy track database changes? flask flask

How does SQLAlchemy track database changes?


The "cache" of a session is a dict in its identity_map (session.identity_map.dict) that only caches objects for the time of "a single business transaction" , as answered here https://stackoverflow.com/a/5869795.

For different server requests, you have different identity_map. It is not a shared object.

In your scenario, you requested the server 2 separated times. The second time, the identity_map is a new one (you can easily check it by printing out its pointer), and has nothing in cache. Consequently the session will request the database and get you the updated answer. It does not "track change" as you might think.

So, to your question, you don't need to do session.commit() before a query if you have not done a query for the same object in the same server request.

Hope it helps.