gpt4 book ai didi

python - Tornado 协程

转载 作者:太空狗 更新时间:2023-10-29 17:23:25 25 4
gpt4 key购买 nike

我正在尝试学习 tornado 协程,但使用以下代码时出现错误。

Traceback (most recent call last):
File "D:\projekty\tornado\env\lib\site-packages\tornado\web.py", line 1334, in _execute
result = yield result
File "D:\projekty\tornado\env\lib\site-packages\tornado\gen.py", line 628, in run
value = future.result()
File "D:\projekty\tornado\env\lib\site-packages\tornado\concurrent.py", line 109, in result
raise_exc_info(self._exc_info)
File "D:\projekty\tornado\env\lib\site-packages\tornado\gen.py", line 631, in run
yielded = self.gen.throw(*sys.exc_info())
File "index.py", line 20, in get
x = yield 'test'
File "D:\projekty\tornado\env\lib\site-packages\tornado\gen.py", line 628, in run
value = future.result()
File "D:\projekty\tornado\env\lib\site-packages\tornado\concurrent.py", line 111, in result
raise self._exception
BadYieldError: yielded unknown object 'test'

代码:

from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, Application, url
from tornado import gen

class HelloHandler(RequestHandler):
@gen.coroutine
def get(self):
x = yield 'test'
self.render('hello.html')


def make_app():
return Application(
[url(r"/", HelloHandler)],
debug = True
)

def main():
app = make_app()
app.listen(8888)
IOLoop.instance().start()

main()

最佳答案

正如 Lutz Horn 指出的那样,tornado.coroutine 装饰器要求您仅生成 Future 对象或某些包含 Future 对象的容器。所以尝试生成 str 会引发错误。我认为你缺少的部分是协程中你想调用 yield something() 的任何地方,something 也必须是协程,或者返回 future 。例如,您可以像这样修复您的示例:

from tornado.gen import Return

class HelloHandler(RequestHandler):
@gen.coroutine
def get(self):
x = yield self.do_test()
self.render('hello.html')

@gen.coroutine
def do_test(self):
raise Return('test')
# return 'test' # Python 3.3+

甚至这样(虽然通常你不应该这样做):

class HelloHandler(RequestHandler):
@gen.coroutine
def get(self):
x = yield self.do_test()
self.render('hello.html')

def do_test(self):
fut = Future()
fut.set_result("test")
return fut

当然,这些都是人为的例子;由于我们实际上并没有在 do_test 中执行任何异步操作,因此没有理由将其设为协程。通常你会在那里做某种异步 I/O。例如:

class HelloHandler(RequestHandler):
@gen.coroutine
def get(self):
x = yield self.do_test()
self.render('hello.html')

@gen.coroutine
def do_test(self):
http_client = AsyncHTTPClient()
out = yield http_client.fetch("someurl.com") # fetch is a coroutine
raise Return(out.body)
# return out.body # Python 3.3+

关于python - Tornado 协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27043076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com