我们正在使用momoko并在 tornado 应用程序中使用以下标准设置异步连接到数据库:
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
通常用于从数据库中读取,而不是用于在那里写入/更新数据?