在使用 Tornado 的过程中产生了以下疑问:

  • 什么时候需要给函数增加 @tornado.gen.coroutine
  • 什么时候调用函数需要 yield

@tornado.gen.coroutineyield 是如何工作的

包含 yield 的函数是一个 generator[1]。@gen.coroutine 通过 yield 与 generator 沟通、通过返回 Future 与协程的调用者沟通。

具体沟通情况:

  • @gen.coroutine 收到从 generator 返回的 Future
  • "unwraps" Future 获得结果
  • 将结果发送回 generator 以作为 yield 表达式的结果

如何调用协程

上文提到,

@gen.coroutine 通过返回 Future 与协程的调用者沟通

所以我们必须 "unwraps" 这个 Future 才能得到结果。

所以在绝大部分情况下,任何调用协程的函数本身必须是一个协程,并且在调用中要使用 yield

@gen.coroutine
def good_call():
# yield will unwrap the Future returned by divide() and raise
# the exception.
yield divide(1, 0)

注意,yield 只有在 @gen.coroutine 中才会 "unwraps" 一个 Future,如果没有 @gen.coroutine,那么 yield 只会将该函数变为一个而普通的生成器,比如下面两个例子。

  • 错误的
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.gen import Return @tornado.gen.coroutine
def call_me():
raise Return('result') def f():
r = yield call_me()
print(r) # tornado.gen.BadYieldError: yielded unknown object <generator object f at 0x104a34320> IOLoop.current().run_sync(f)

错误的原因是:run_sync 会调用 f(),然后尝试将 f() 的结果转换为 Future,转换的函数如下:

# env/lib/python2.7/site-packages/tornado/gen.py:1259
def convert_yielded(yielded):
"""Convert a yielded object into a `.Future`. The default implementation accepts lists, dictionaries, and Futures. If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example:: @convert_yielded.register(asyncio.Future)
def _(asyncio_future):
return tornado.platform.asyncio.to_tornado_future(asyncio_future) .. versionadded:: 4.1
"""
# Lists and dicts containing YieldPoints were handled earlier.
if yielded is None:
return moment
elif isinstance(yielded, (list, dict)):
return multi(yielded)
elif is_future(yielded):
return yielded
elif isawaitable(yielded):
return _wrap_awaitable(yielded)
else:
raise BadYieldError("yielded unknown object %r" % (yielded,))

由于 f() 返回的是一个 generator 对象,不符合转换的要求,所以报错。如果给 f() 加上 @tornado.gen.coroutine,那么装饰器会将 f() 返回的结果转换为 Future,符合 elif is_future(yielded):,也就能顺利运行。

  • 正确的
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.gen import Return @tornado.gen.coroutine
def call_me():
raise Return('result') @tornado.gen.coroutine
def f():
r = yield call_me()
print(r) # result IOLoop.current().run_sync(f)

总结

  • 当调用一个协程时,@tornado.gen.coroutineyield 必须同时出现调用函数中
  • 如果只是在协程中执行操作或者直接返回结果,有 @tornado.gen.coroutine 和 return(raise Return)就够了

参考

  1. https://docs.python.org/2.4/ref/yield.html
  2. http://www.tornadoweb.org/en/stable/guide/coroutines.html#how-it-works

Tornado @tornado.gen.coroutine 与 yield的更多相关文章

  1. 使用tornado的gen.coroutine进行异步编程

    在tornado3发布之后,强化了coroutine的概念,在异步编程中,替代了原来的gen.engine, 变成现在的gen.coroutine.这个装饰器本来就是为了简化在tornado中的异步编 ...

  2. Tornado中gen.coroutine详解

    1.gen.coroutine的作用 自动执行生成器 2.Future对象 在介绍异步使用之前,先了解一下Future对象的作用. Future简单可以理解为一个占位符,将来会执行的对象,类似java ...

  3. Tornado源码分析系列之一: 化异步为'同步'的Future和gen.coroutine

    转自:http://blog.nathon.wang/2015/06/24/tornado-source-insight-01-gen/ 用Tornado也有一段时间,Tornado的文档还是比较匮乏 ...

  4. 如何捕捉@tornado.gen.coroutine里的异常

    from tornado import gen from tornado.ioloop import IOLoop @gen.coroutine def throw(a,b): try: a/b ra ...

  5. 使用tornado的gen模块改善程序性能

    之前在公司的一个模块,需要从另一处url取得数据,我使用了Python的一个很著名的lib,叫做requests.但是这样做极大的降低了程序的性能,因为tornado是单线程的,它使用了所谓的reac ...

  6. yield与gen.coroutine

    def d(): for i in range(2): yield i def b(): yield d() print("b") yield "bb" def ...

  7. 【Unity】协程Coroutine及Yield常见用法

    最近学习协程Coroutine,参考了别人的文章和视频教程,感觉协程用法还是相当灵活巧妙的,在此简单总结,方便自己以后回顾.Yield关键字的语意可以理解为“暂停”. 首先是yield return的 ...

  8. tornado异步请求的理解(转)

    tornado异步请求的理解 http://www.kankanews.com/ICkengine/archives/88953.shtml 官网第一段话: Tornado is a Python w ...

  9. PythonWEB框架之Tornado

    前言 Tornado(龙卷风)和Django一样是Python中比较主流的web框架,Tornado 和现在的主流 Web 服务器框架也有着明显的区别:Tornado自带socket,并且实现了异步非 ...

随机推荐

  1. Linux Kernel源码浏览

    https://www.kernel.org/http://lxr.linux.no/

  2. Decoration3:增删改的实现

    下面我们完成数据的增加.删除.修改,这里的主要知识就是前端Angularjs,遇到的问题 1.路由组件采用ui.router,链接的写法有两种: <a href="#/coach/cr ...

  3. C++虚函数解析(转载)

    虚函数详解第一篇:对象内存模型浅析 C++中的虚函数的内部实现机制到底是怎样的呢?     鉴于涉及到的内容有点多,我将分三篇文章来介绍.     第一篇:对象内存模型浅析,这里我将对对象的内存模型进 ...

  4. Netty 源码分析之 番外篇 Java NIO 的前生今世

    简介 Java NIO 是由 Java 1.4 引进的异步 IO. Java NIO 由以下几个核心部分组成: Channel Buffer Selector NIO 和 IO 的对比 IO 和 NI ...

  5. Mac下修改应用程序的菜单快捷键!

    点击左上角苹果按钮,系统偏好设置 > 键盘 > 快捷键 > 应用快捷键 点击右下角添加按钮,选择chrome程序,输入菜单中文名以及快捷键 1.如何用F5刷新 鼠标悬停在左上角的刷新 ...

  6. 关于Unity中的新手编码技巧

    写代码遇到报错,问题怎么办?怎么查看unity代码的接口?函数参数不记得了怎么办? 解决方法: 1.选择不懂的函数或类,按F12,跳转到代码的定义,自己去看就可知道了. 2.有的时候,选择一个函数,按 ...

  7. lmbench

    lmbench作为性能检测工具的一种,提供内存,网络,内核等多方面的测试工具.是benchmark众多功能测试软件中的一种.几天了解了下,记录于此. 参考链接 http://www.bitmover. ...

  8. MyBatis 使用简单的 XML或注解用于配置和原始映射

    MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis .My ...

  9. before伪类的超有用应用技巧——水平菜单竖线分隔符

    方法一.li前面加before伪类 <!doctype html> <html dir="ltr" lang="zh-CN"> < ...

  10. php如何优化压缩的图片

    php程序开发中经常涉及到生成缩略图,利用php生成缩略图这个过程本身没难度,但是你知道php能够优化调节生成的缩略图的质量吗?也就是说php能够控制生成缩略图的清晰度以及生成后的缩略图的体积.下面我 ...