产生Future时的Python BadYieldError

时间:2016-05-31 18:27:17

标签: python tornado future yield coroutine

我是使用协程编程的新手,我正在尝试使用Python 2.7.10为Tornado Web服务器的自定义数据库构建数据库接口。但是,我一直在BadYieldError。我觉得这可能是我不理解如何在Python的tornado.gen.coroutine中充分使用yield。我认为我如何产生未来可能有问题。

这是我保持失败的代码,其中第15行的testGet函数是外部数据库访问的模拟。

from tornado import gen
import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        response = "Hello, world"
        response = yield db_interface("default", "user_query")
        self.write(str(response))


# meant to demonstrate
def testGet(query):
    gen.sleep(2)
    response = query
    return response


@gen.coroutine
def db_interface(db, key):
    print str(db)
    d = yield testGet(key)
    raise gen.Return(d)


def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8889)
    tornado.ioloop.IOLoop.current().start()

输出:

default
ERROR:tornado.application:Uncaught exception GET / (127.0.0.1)
HTTPServerRequest(protocol='http', host='127.0.0.1:8889', method='GET', uri='/', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Accept-Language': 'en-CA,en;q=0.8,fr;q=0.6', 'Accept-Encoding': 'gzip, deflate, sdch', 'Host': '127.0.0.1:8889', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Dnt': '1', 'Connection': 'keep-alive', 'Cookie': 'ui-auth-127.0.0.1%3A8091=4f1301ef98f1b6fbd80ad059cd5aa2dc', 'Cache-Control': 'max-age=0', 'Upgrade-Insecure-Requests': '1'})
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/tornado/web.py", line 1415, in _execute
    result = yield result
  File "/usr/local/lib/python2.7/site-packages/tornado/gen.py", line 870, in run
    value = future.result()
  File "/usr/local/lib/python2.7/site-packages/tornado/concurrent.py", line 215, in result
    raise_exc_info(self._exc_info)
  File "/usr/local/lib/python2.7/site-packages/tornado/gen.py", line 876, in run
    yielded = self.gen.throw(*exc_info)
  File "test.py", line 12, in get
    response = yield db_interface("default", "user_query")
  File "/usr/local/lib/python2.7/site-packages/tornado/gen.py", line 870, in run
    value = future.result()
  File "/usr/local/lib/python2.7/site-packages/tornado/concurrent.py", line 215, in result
    raise_exc_info(self._exc_info)
  File "/usr/local/lib/python2.7/site-packages/tornado/gen.py", line 876, in run
    yielded = self.gen.throw(*exc_info)
  File "test.py", line 26, in db_interface
    d = yield testGet(key)
  File "/usr/local/lib/python2.7/site-packages/tornado/gen.py", line 870, in run
    value = future.result()
  File "/usr/local/lib/python2.7/site-packages/tornado/concurrent.py", line 215, in result
    raise_exc_info(self._exc_info)
  File "/usr/local/lib/python2.7/site-packages/tornado/gen.py", line 956, in handle_yield
    self.future = convert_yielded(yielded)
  File "/usr/local/lib/python2.7/site-packages/tornado/gen.py", line 1026, in convert_yielded
    raise BadYieldError("yielded unknown object %r" % (yielded,))
BadYieldError: yielded unknown object 'user_query'
ERROR:tornado.access:500 GET / (127.0.0.1) 2011.67ms

我一直在努力寻找如何在Tornado's official documentationthis blog上正确地做到这一点,但我认为我无法完全理解他们所说的内容如何使用协同程序。

1 个答案:

答案 0 :(得分:2)

testGet转换为这样的协程,以便它返回未来:

@gen.coroutine
def testGet(query):
    gen.sleep(2)
    raise gen.Return(query)

或者不要在其上使用yieldd = testGet(key)

如果你这样做,代码就可以了。您应该在返回yield的函数上使用Future