python3 asyncio:堆栈中的所有函数都必须使用await/async

Tom*_*mmy 5 python-3.x python-asyncio

使用时await/async,它是否必须“一路向上”,这意味着调用链中的每个函数都必须使用它吗?

例如:

def a():
    # can't call b() here

async def b():
    return await c

async def c():
    return ...
Run Code Online (Sandbox Code Playgroud)

我最近在 gevent 下运行的 Flask 应用程序的上下文中想知道这一点,其中一个端点是一个长时间运行的调用,应该“检查”,同时不阻止其他调用

def handler0():
    # short running
    return ...

def handler():  # blocks handler0
    return await some_long_thing()

async def some_long_thinig():
    # ..do somethiing
    return ...
Run Code Online (Sandbox Code Playgroud)

Mik*_*mov 2

调用链中的每个函数都必须使用它吗?

当您使用asyncio模块时,每个函数都await应该定义为async(应该是协程本身)。

大多数顶级协程通常是脚本的主要入口点,并通过事件循环使用asyncio.run()或类似函数执行。

这就是asyncio 设计的方式:这样你总是知道上下文是否可以或不能在特定位置切换。