momokoを使用しており、tornado アプリケーションでの db への非同期接続には次の標準設定があります。
class BaseHandler(tornado.web.RequestHandler):
@property
def db(self):
# Create a database connection when a request handler is called
# and store the connection in the application object.
if not hasattr(self.application, 'db'):
self.application.db = momoko.AsyncClient({
'host': 'localhost',
'database': 'momoko',
'user': 'frank',
'password': '',
'min_conn': 1,
'max_conn': 20,
'cleanup_timeout': 10
})
return self.application.db
ある日、次のようなコードがアプリケーションをブロックすることがわかりました。
fail = yield gen.Task(self.db.execute, 'BEGIN; SELECT * FROM non_existing_table; END;')
頭に浮かんだ最初のアイデアは次のとおりです。
try:
fail = yield gen.Task(self.db.execute, 'BEGIN; SELECT * FROM non_existing_table; END;')
except:
reconnect()
主題を掘り下げた後、次のようなことを行う方が良いことがわかりました。
try:
fail = yield gen.Task(self.db.execute, 'BEGIN; SELECT * FROM non_existing_table; END;')
except:
yield gen.Task(self.db.execute, 'ROLLBACK;')
最後に、 momoko のソース コードを調べたところ、トランザクションにはブロッキング クライアントを使用する方がよいことがわかりました。
したがって、 BaseHandler は次のように変換されます。
class BaseHandler(tornado.web.RequestHandler):
@property
def db(self):
# Create a database connection when a request handler is called
# and store the connection in the application object.
if not hasattr(self.application, 'db'):
self.application.db = momoko.AsyncClient({
'host': 'localhost',
'database': 'momoko',
'user': 'frank',
'password': '',
'min_conn': 1,
'max_conn': 20,
'cleanup_timeout': 10
})
return self.application.db
@property
def bdb(self):
# Create a database connection when a request handler is called
# and store the connection in the application object.
if not hasattr(self.application, 'bdb'):
self.application.bdb = momoko.BlockingClient({
'host': 'localhost',
'database': 'momoko',
'user': 'frank',
'password': '',
'min_conn': 1,
'max_conn': 20,
'cleanup_timeout': 10
})
return self.application.bdb
今私の質問...でトランザクションを使用する安全な方法はありますAsyncClient
か? またはAsyncClient
、データの書き込み/更新ではなく、データベースからの読み取りに一般的に使用されますか?