2012-10-01 57 views
2

我们使用momoko并具有以下标准设置为异步连接在龙卷风应用到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;') 

最后,探索桃子的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通常用于从数据库中读取数据,而不是在那里写入/更新数据?

回答

1

我正在研究Momoko 1.0.0,我刚刚发布了第一个测试版。交易是新功能之一。这是我在邮件列表后:1.0.0之前https://groups.google.com/forum/?fromgroups=#!topic/python-tornado/7TpxBQvbHZM

版本不支持事务,因为每次你运行execute有一种可能性,即AsyncClient会为您挑选一个新的连接,你将无法回滚您如果出现任何问题,交易。

我希望这会有所帮助。 :)

+0

感谢您的伟大的驱动程序。 :) –