非阻塞客户端的交易?

时间:2012-10-01 13:35:53

标签: python sql postgresql asynchronous tornado

我们正在使用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;')

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

1 个答案:

答案 0 :(得分:1)

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

1.0.0之前的版本不支持事务,因为每次运行execute时,AsyncClient都可能会为您选择一个新连接,并且您将无法回滚事务如果出现任何问题。

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