Sqlalchemy query returns incorrect and outdated results (for sqlite engine)

≡放荡痞女 提交于 2019-12-08 12:20:43

问题


I'm using sqlalchemy with sqlite engine (development server) and just discovered that after update query, queries in next web-requests return outdated data set (that depends on fact which thread is used for the request, as I understand there is a pool of threads).

I'm using scoped_session and the other recommended stuff from docs (DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))).

Here is the example of web requests and what's executed there.

request-1:thread-1: SELECT * FROM table WHERE id=1 -> (id:1, data:1)
request-2:thread-2: UPDATE table SET data=2 WHERE id=1; COMMIT
request-3:thread-1: SELECT * FROM table WHERE id=1 -> (id:1, data:1) // STILL data:1 !
request-4:thread-4: SELECT * FROM table WHERE id=1 -> (id:1, data:2) // NEW DATA!     
request-5:thread-1: SELECT * FROM table WHERE id=1 -> (id:1, data:1) // AND AGAIN OLD DATA!

What is this? How can I avoid this behaviour? In the example above all web requests are executed in consecutive order, so SQL-queries do not intersect.


回答1:


You need to activate the pyramid_tm tween.

[app:main]

pyramid.includes =
    pyramid_tm

The tween commits transactions after each request, implicitly starting a new transaction when a new request comes in.

When you do not start a new transaction, the old transaction will not see data committed in other transactions (threads); this is a inherent feature of database transactions, as not doing so would lead to inconsistency errors.




回答2:


You could issue a Session.refresh with the database object you want to get the value of.



来源:https://stackoverflow.com/questions/18683909/sqlalchemy-query-returns-incorrect-and-outdated-results-for-sqlite-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!