sách gpt4 ăn đã đi

python - Sự khác biệt giữa lốc xoáy.gen.engine và lốc xoáy.gen.coroutine

In lại 作者:太空狗 更新时间:2023-10-30 01:01:39 28 4
mua khóa gpt4 giày nike

经过 tornado.gen tài liệu有人可以帮我理解 tornado.gen.coroutine 和 tornado.gen.engine 之间的确切区别

câu trả lời hay nhất

BẰNG gen.engine 的 Tornado 文档所说:

This decorator is similar to coroutine, except it does not return a Future and the callback argument is not treated specially.

BẰNG gen.coroutine 文档所说

From the caller’s perspective, @gen.coroutine is similar to the combination of @return_future and @gen.engine.

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:
thử:
result = func(*args, **kwargs)
except (Return, StopIteration) as e:
result = getattr(e, 'value', None)
khác:
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()
trở lại
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):
thử:
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:
thử:
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
khác:
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.coroutinegọi lại kwarg 有一些特殊处理,它构建/返回一个 tương lai @gen.engine 有一些代码会在您尝试从中返回某些内容时专门抛出错误,而不是将其放入 Tương lai ở giữa.

关于python - tornado.gen.engine 与 tornado.gen.coroutine 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502338/

28 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress