我有幾個python應用程序(單獨的進程),都使用Flask-SQLAlchemy來訪問sqlite數據庫。其中一個是使用asyncio模塊(但仍然是Flask應用程序)設置的,另一個是Flask-RESTful API。SQLAlchemy數據在連接間不一致
我看到一個問題,其中由Flask-RESTful API寫入數據庫的數據沒有被asyncio應用程序看到。我讀過這可能是由於隔離級別(How to disable SQLAlchemy caching?)。如果我使用session.expire_all()
,問題就會消失。
那麼這是真的由於隔離水平?我的理解是,sqlite幾乎所有的時候都使用serializable isolation level(我相信這是我的情況)。正在編寫的REST API正在提交它的事務,但除非我撥打session.expire_all()
,否則asyncio代碼不會看到它們。這看起來像事務隔離問題,更像SQLAlchemy的問題,但我不是100%確定。
我是否必須始終記得在查詢數據庫之前先撥打session.expire_all()
?是否有更好的方法來保持應用程序之間的一致性?
下面是一些代碼,如果有幫助:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
@asyncio.coroutine
def grab_data_off_queue(self):
while True:
try:
hit = self.hit_queue.get(False)
# required for this session to see the changes made by REST api
db.session.expire_all()
rows = MyTable.query.filter_by.all()
for row in rows:
# the REST API is setting field_2 to 123,
# but this session cannot see those changes
if row.field_2 == 123:
do_something() #execution never gets here
這裏是REST API:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
class MyApi(Resource):
def put(self, id):
row = MyTable.query.filter_by(table_id=id).one()
row.field_2 = 123
db.session.commit()
return '', 204
REST api代碼正在調用'session.commit()'。你是說即使只是查詢數據而不更新或插入任何內容的異步代碼也需要調用'session.commit()'以及? – d512