卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

tornado出现gen.Return(\"hello\")的解决方案

tornado出现gen.return(

报错的原因

python 中,Tornado 是一个基于事件循环的网络框架。它使用了协程来处理并发,gen.Return("hello") 是一种用于在协程中返回值的方法。在使用 Tornado 的异步功能时,使用 gen.Return() 可以在协程中返回值。

如何解决

在 Tornado 中,使用 yield 和 gen.Return() 来返回值。如果想要在协程中返回值,可以使用 yield 和 gen.Return() 来达到目的。

例如:


@gen.coroutine
def my_coroutine():
result = yield some_async_call()
raise gen.Return(result)

在函数外使用 asyncio.run() 或 tornado.gen.convert_yielded() 来获得返回值。


result = await my_coroutine()

如果想要在协程中返回值,应该使用 yield 和 gen.Return() 来达到目的。

使用例子

下面是一个简单的例子,在 Tornado 中使用协程并返回值:


import tornado.ioloop
import tornado.gen

@tornado.gen.coroutine
def my_coroutine():
result = yield some_async_call()
raise tornado.gen.Return(result)

def handle_result(result):
print(result)

if __name__ == "__main__":
result = tornado.ioloop.IOLoop.current().run_sync(my_coroutine)
handle_result(result)

这里的 some_async_call() 是一个异步函数。

如果想在函数外获取返回值,可以这样:


result = await my_coroutine()

当然,async/await 语法也可以使用,这就要求在函数前加上 async 修饰符,并且调用函数时使用 await 。


async def my_coroutine():
result = await some_async_call()
return result

在上面的例子中,result 就是返回值,可以在 handle_result() 中进行处理。

卓越飞翔博客
上一篇: 对于pip错误SSLError(\"Can\'t connect to HTTPS URL because the SSL module is not available.\
下一篇: 为什么ValueError(\"operator must be unary (1), binary (2), or ternary (3)\"),怎么解决
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏