python-asyncio TypeError: object dict can't be used in 'await' 表达式

新手上路,请多包涵

我正在使用第三方模块从 API 检索数据。我只是想异步等待模块返回偶尔需要几秒钟并冻结我的应用程序的数据。但是,当我尝试等待对该模块的调用时,我收到了 TypeError:

TypeError: object dict can't be used in 'await' expression

 import thirdPartyAPIwrapper

async def getData():
    retrienveData = await thirdPartyAPIWrapper.data()
    return await retrieveData

def main():
    loop = asncio.get_event_loop()
    data = loop.run_until_complete(getData())
    loop.close
    return data

为什么我不能等待类型(’dict’)?有没有解决的办法?如果带有 asyncio 的 async/await 不能与不返回协程的第三方模块一起使用,那么我的其他选择是什么?

原文由 Riley Hughes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3k
2 个回答

只能等待异步(定义为 async def )函数。整个想法是,这些函数是以特殊方式编写的,可以在不阻塞事件循环的情况下运行( await )。

如果您想从需要相当长的时间执行的常见(定义为 def )函数中获取结果,您可以选择以下选项:

  • 将整个函数重写为异步的
  • 在另一个线程中调用此函数并异步等待结果
  • 在另一个进程中调用此函数并异步等待结果

通常你想选择第二个选项。

以下是如何操作的示例:

 import asyncio
import time
from concurrent.futures import ThreadPoolExecutor

_executor = ThreadPoolExecutor(1)

def sync_blocking():
    time.sleep(2)

async def hello_world():
    # run blocking function in another thread,
    # and wait for it's result:
    await loop.run_in_executor(_executor, sync_blocking)

loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
loop.close()

请阅读 这个关于 asyncio 如何工作的答案。我想这会对你有很大帮助。

原文由 Mikhail Gerasimov 发布,翻译遵循 CC BY-SA 3.0 许可协议

由于 thirdPartyAPIWrapper.data() 是一个正常的同步函数,您应该在另一个线程中调用它。

asgiref 库中有一个辅助函数。

假设我们有一个带有参数的阻塞函数:

 import asyncio
import time

from asgiref.sync import sync_to_async

def blocking_function(seconds: int) -> str:
    time.sleep(seconds)
    return f"Finished in {seconds} seconds"

async def main():
    seconds_to_sleep = 5
    function_message = await sync_to_async(blocking_function)(seconds_to_sleep)
    print(function_message)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

该库中还有一个 async_to_sync 辅助函数。

原文由 Serge 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题