0

我是 python 的新手,甚至是 tornado/momoko 的新手。我正在努力学习 momoko 网站上的一个例子。我使用我的设置配置了 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
4

1 回答 1

0

Momoko是 的包装器psycopg2,而不是mysql.

使用 mysql 尝试使用此页面上列表中的内容:

如果您使用的是 postgresql - 首先尝试以同步方式连接到它。

于 2012-10-25T05:40:13.650 回答