python - 'yield from' 替代 async def 函数
问题描述
在一个几乎 100% 异步的类中,我需要以同步(顺序)方式执行一些代码(当前是协程)。所以我创建了这个函数:
@asyncio.coroutine
def execute_sequential(self, doo):
for key in doo:
yield from self.fetch_one_fin_instr_hist_data(doo[key])
我用这些命令执行它:
tasks = [self.execute_sequential(doo)]
await asyncio.gather(*tasks)
fetch_one_fin_instr_hist_data必须是协程,因为它是由异步函数调用的。它具有以下签名:
async def fetch_one_fin_instr_hist_data(self, obj):
一切正常。不幸的@asyncio.coroutine
是,不推荐使用,所以我应该用async def
关键字替换它。yield from
不async def
支持。
我尝试了以下方法:
async def execute_sequential(self, doo):
for key in doo:
for obj in self.fetch_one_fin_instr_hist_data(doo[key]):
yield obj
但在线
for obj in self.fetch_one_fin_instr_hist_data(doo[key]):
我得到错误:
预期类型 'collections.Iterable',得到了 'Coroutine[Any, Any, None]'
有没有办法将协程转换为可迭代的?或者更好的是,在这种情况下,什么可以替代产量?
解决方案
虽然yield from
对于创建生成器仍然有效,但此特定内容已被await
关键字替换。
@asyncio.coroutine
def execute_sequential(self, doo):
for key in doo:
yield from self.fetch_one_fin_instr_hist_data(doo[key])
现在应该是
async def execute_sequential(self, doo):
for key in doo:
await self.fetch_one_fin_instr_hist_data(doo[key])
推荐阅读
- sql - 如何使用 PostgreSQL 从数组和 array_agg 中排除或删除 NULL 值
- angular - 生产角度应用程序在 Google 搜索中显示为测试模式
- plotly-dash - 如何通过 LAN 访问 Plotly-Dash 应用服务器
- c - 该程序多次检测开关而不是一次(轮询问题)
- angular - 测试 - 没有 TranslateService 的提供者
- python - adb 屏幕流式传输到 python + opencv
- nginx - nginx 使用模块编译
- python - SyntaxError:非默认参数遵循python中的默认参数
- javascript - 防止按下特定链接/按钮时关闭下拉菜单
- momentjs - 使用 moment.js 验证时间