python-3.x - python3 asyncio:堆栈中的所有函数都必须使用等待/异步吗
问题描述
使用时await/async
,是否必须“一直向上”,意思是调用链中的每个函数都必须使用它吗?
例如:
def a():
# can't call b() here
async def b():
return await c
async def c():
return ...
我最近在 gevent 下运行的烧瓶应用程序的上下文中想知道这一点,其中一个端点是一个长时间运行的调用,应该“检查”,而不是阻塞其他调用
def handler0():
# short running
return ...
def handler(): # blocks handler0
return await some_long_thing()
async def some_long_thinig():
# ..do somethiing
return ...
解决方案
调用链中的每个函数都必须使用它吗?
当您使用asyncio
模块时,每个功能都await
应该被定义为async
(应该是协程本身)。
大多数顶级协程通常是脚本的主要入口点,并由事件循环使用asyncio.run()或类似函数执行。
这就是asyncio
设计方式:通过这种方式,您始终知道上下文是否可以在特定位置切换。
推荐阅读
- typescript - 如何使用 nuxt-property-decorator 中的 Prop 控制子组件信息形成主组件?
- kentico - 使用带有预生成 HTML 的 Kentico CMS
- webpack - Webpack html-critical-webpack-plugin
- algorithm - 更有效地找到差异较小的最大区域
- groovy - Spock 断言函数调用
- kubernetes - 在 pod 中同步数据
- c# - NHibernate 将 sql 查询转换为 NHibernate QueryOver 查询
- json - 如何使用 jq 或任何工具合并目录中的多个 json 文件?
- plot - geopandas plotting - 识别地图之外的位置
- python - 在为 pip 安装安装不同的缓存后,Docker 实验构建仍然使用系统缓存