我们正在使用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的source code之后,我发现使用阻塞客户端进行事务处理更好。
因此,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通常用于从数据库读取数据,而不是用于写入/更新数据?
发布于 2012-12-17 08:03:15
我正在开发Momoko 1.0.0,我刚刚发布了第一个测试版。事务是新特性之一。这是我在邮件列表上的帖子:https://groups.google.com/forum/?fromgroups=#!topic/python-tornado/7TpxBQvbHZM
1.0.0之前的版本不支持事务,因为每次您运行execute时,AsyncClient都有可能为您挑选一个新的连接,如果出现任何错误,您将无法回滚您的事务。
我希望这会有一点帮助。:)
https://stackoverflow.com/questions/12674384
复制相似问题