我如何让momoko工作?

时间:2012-10-23 21:36:17

标签: python mysql tornado

我是python的新手,甚至是龙卷风/ momoko的新手。我正在努力解决momoko's website的一个例子。我有使用我的设置配置的database.cfg文件。

#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import gen
import momoko
import settings

class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return self.application.db


class OverviewHandler(BaseHandler):
    def get(self):
        self.write('''
<ul>
<li><a href="/query">A single query</a></li>
<li><a href="/batch">A batch of queries</a></li>
<li><a href="/chain">A chain of queries</a></li>
<li><a href="/multi_query">Multiple queries executed with gen.Task</a></li>
<li><a href="/callback_and_wait">Multiple queries executed with gen.Callback and gen.Wait</a></li>
</ul>
''')
        self.finish()


class SingleQueryHandler(BaseHandler):
    @tornado.web.asynchronous
    @gen.engine
    def get(self):
        # One simple query
        cursor = yield gen.Task(self.db.execute, 'SELECT 42, 12, %s, 11;', (25,))
        self.write('Query results: %s' % cursor.fetchall())
        self.finish()


class BatchQueryHandler(BaseHandler):
    @tornado.web.asynchronous
    @gen.engine
    def get(self):
        # These queries are executed all at once and therefore they need to be
        # stored in an dictionary so you know where the resulting cursors
        # come from, because they won't arrive in the same order.
        cursors = yield gen.Task(self.db.batch, {
            'query1': ['SELECT 42, 12, %s, %s;', (23, 56)],
            'query2': 'SELECT 1, 2, 3, 4, 5;',
            'query3': 'SELECT 465767, 4567, 3454;'
        })

        for key, cursor in cursors.items():
            self.write('Query results: %s = %s<br>' % (key, cursor.fetchall()))
        self.finish()


class QueryChainHandler(BaseHandler):
    @tornado.web.asynchronous
    @gen.engine
    def get(self):
        # Execute a list of queries in the order you specified
        cursors = yield gen.Task(self.db.chain, (
            ['SELECT 42, 12, %s, 11;', (23,)],
            'SELECT 1, 2, 3, 4, 5;'
        ))

        for cursor in cursors:
            self.write('Query results: %s<br>' % cursor.fetchall())
        self.finish()


class MultiQueryHandler(BaseHandler):
    @tornado.web.asynchronous
    @gen.engine
    def get(self):
        cursor1, cursor2, cursor3 = yield [
            gen.Task(self.db.execute, 'SELECT 42, 12, %s, 11;', (25,)),
            gen.Task(self.db.execute, 'SELECT 42, 12, %s, %s;', (23, 56)),
            gen.Task(self.db.execute, 'SELECT 465767, 4567, 3454;')
        ]

        self.write('Query 1 results: %s<br>' % cursor1.fetchall())
        self.write('Query 2 results: %s<br>' % cursor2.fetchall())
        self.write('Query 3 results: %s' % cursor3.fetchall())

        self.finish()


class CallbackWaitHandler(BaseHandler):
    @tornado.web.asynchronous
    @gen.engine
    def get(self):

        self.db.execute('SELECT 42, 12, %s, 11;', (25,),
            callback=(yield gen.Callback('q1')))
        self.db.execute('SELECT 42, 12, %s, %s;', (23, 56),
            callback=(yield gen.Callback('q2')))
        self.db.execute('SELECT 465767, 4567, 3454;',
            callback=(yield gen.Callback('q3')))

        cursor1 = yield gen.Wait('q1')
        cursor2 = yield gen.Wait('q2')
        cursor3 = yield gen.Wait('q3')

        self.write('Query 1 results: %s<br>' % cursor1.fetchall())
        self.write('Query 2 results: %s<br>' % cursor2.fetchall())
        self.write('Query 3 results: %s' % cursor3.fetchall())

        self.finish()


def main():
    try:
        tornado.options.parse_command_line()
        application = tornado.web.Application([
            (r'/', OverviewHandler),
            (r'/query', SingleQueryHandler),
            (r'/batch', BatchQueryHandler),
            (r'/chain', QueryChainHandler),
            (r'/multi_query', MultiQueryHandler),
            (r'/callback_and_wait', CallbackWaitHandler),
        ], debug=True)

        application.db = momoko.AsyncClient({
            'host': settings.host,
            'port': settings.port,
            'database': settings.database,
            'user': settings.user,
            'password': settings.password,
            'min_conn': settings.min_conn,
            'max_conn': settings.max_conn,
            'cleanup_timeout': settings.cleanup_timeout
        })

        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(8888)
        tornado.ioloop.IOLoop.instance().start() # the problem lies here, I believe
    except KeyboardInterrupt:
        print('Exit')


if __name__ == '__main__':
    main()

当我运行脚本时,我收到错误:

[E 121023 15:31:07 ioloop:337] Exception in I/O handler for fd 6
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 327, in start
        self._handlers[fd](fd, events)
      File "/usr/local/lib/python2.7/dist-packages/momoko/pools.py", line 313, in _io_callback
        state = self._conn.poll()
    OperationalError: asynchronous connection failed

我可以连接到网络服务器。如果我输入“http:// localhost:8888 /”,我会看到5个链接(即“单个查询”,“一批查询”等)。然而,当我点击一个时,我得到:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1021, in _stack_context_handle_exception
    raise_exc_info((type, value, traceback))
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 265, in _nested
    if exit(*exc):
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 161, in __exit__
    return self.exception_handler(type, value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 114, in handle_exception
    return runner.handle_exception(typ, value, tb)
  File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 388, in handle_exception
    self.run()
  File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 343, in run
    yielded = self.gen.throw(*exc_info)
  File "/home/desktop-admin/Desktop/eclipse/workspace/jive_backend/test.py", line 35, in get
    cursor = yield gen.Task(self.db.execute, 'SELECT 42, 12, %s, 11;', (25,))
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 258, in _nested
    yield vars
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 228, in wrapped
    callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/momoko/pools.py", line 313, in _io_callback
    state = self._conn.poll()
OperationalError: asynchronous connection failed

1 个答案:

答案 0 :(得分:0)

Momokopsycopg2的包装,不适用于mysql

使用mysql尝试使用this page上的列表中的内容:

如果您正在使用postgresql - 请先尝试以同步方式连接到它。