代码之家  ›  专栏  ›  技术社区  ›  Tommy

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

  •  1
  • Tommy  · 技术社区  · 6 年前

    使用时 await/async

    例如。:

    def a():
        # can't call b() here
    
    async def b():
        return await c
    
    async def c():
        return ...
    

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

    def handler0():
        # short running
        return ...
    
    def handler():  # blocks handler0
        return await some_long_thing()
    
    async def some_long_thinig():
        # ..do somethiing
        return ...
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   Mikhail Gerasimov    6 年前

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

    当你使用 asyncio 模块化每个功能 await async (应该是一个协同活动本身)。

    大多数顶级协同通常是脚本的主要入口点,并由事件循环使用 asyncio.run()

    这就是为什么 designed :这样,您就可以知道上下文是否可以在特定位置进行切换。