我对使用协同程序编程相当陌生,我正在尝试使用Python2.7.10为Tornado web服务器的自定义数据库构建一个数据库接口。但是,我一直得到一个BadYieldError
。我觉得这可能是我不明白如何将tornado.gen.coroutine
与Python的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()
输出:
^{pr2}$我一直在尝试如何在Tornado's official documentation和{a2}上正确地执行此操作,但我不认为我能够完全理解他们对如何使用协同程序的看法。在
或者将
testGet
转换为这样的协同例程,以便它返回一个future:或者不要在上面使用
yield
:d = testGet(key)
。在如果你这样做的话,代码就有效了。您应该在返回
Future
s的函数上使用yield
相关问题 更多 >
编程相关推荐