大佬教程收集整理的这篇文章主要介绍了Tornado.gen.engine v / s tornado.gen.coroutine的差异,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
正如龙卷风文档所述gen.ENGIne
:
正如gen.coroutIne
文档所说
gen.ENGIne
基本上是协程所做的较旧的,精简的版本。如果要编写新代码,则应遵循文档的建议并始终使用tornado.gen.coroutIne
。
如果您查看这两个函数的代码(去除了文档),这是很明显的。
发动机:
def ENGIne(funC):
@functools.wraps(funC)
def wrapper(*args, **kwargs):
runner = None
def handle_exception(typ, value, tb):
if runner is not None:
return runner.handle_exception(typ, value, tb)
return false
with ExceptionStackContext(handle_exception) as deactivate:
try:
result = func(*args, **kwargs)
except (Return, stopiteration) as e:
result = getattr(e, 'value', NonE)
else:
if isinstance(result, types.GeneratorTypE):
def final_callBACk(value):
if value is not None:
raise ReturnValueIgnoredError(
"@gen.ENGIne functions cAnnot return values: "
"%r" % (value,))
assert value is None
deactivate()
runner = Runner(result, final_callBACk)
runner.run()
return
if result is not None:
raise ReturnValueIgnoredError(
"@gen.ENGIne functions cAnnot return values: %r" %
(result,))
deactivate()
# no yIEld, so we're done
return wrapper
协程:
def coroutIne(funC):
@functools.wraps(funC)
def wrapper(*args, **kwargs):
runner = None
future = TraceBACkFuture()
if 'callBACk' in kwargs:
callBACk = kwargs.pop('callBACk')
Ioloop.current().add_future(
future, lambda future: callBACk(future.result()))
def handle_exception(typ, value, tb):
try:
if runner is not None and runner.handle_exception(typ, value, tb):
return True
except Exception:
typ, value, tb = sys.exc_info()
future.set_exc_info((typ, value, tb))
return True
with ExceptionStackContext(handle_exception) as deactivate:
try:
result = func(*args, **kwargs)
except (Return, stopiteration) as e:
result = getattr(e, 'value', NonE)
except Exception:
deactivate()
future.set_exc_info(sys.exc_info())
return future
else:
if isinstance(result, types.GeneratorTypE):
def final_callBACk(value):
deactivate()
future.set_result(value)
runner = Runner(result, final_callBACk)
runner.run()
return future
deactivate()
future.set_result(result)
return future
return wrapper
乍一看,这两个都可能很难理解。但是,很明显,该代码非常相似,除了@gen.coroutIne
对callBACk
kwarg进行了一些特殊处理之外,它还会生成/返回aFuture
。@gen.ENGIne
如果您尝试从中返回某些内容而不是将其放入,则其中的某些代码专门抛出了错误Future
。
以上是大佬教程为你收集整理的Tornado.gen.engine v / s tornado.gen.coroutine的差异全部内容,希望文章能够帮你解决Tornado.gen.engine v / s tornado.gen.coroutine的差异所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。