我正在使用第三方模块从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不能与不返回协程的第三方模块一起工作,那么我还有其他选择吗?
发布于 2018-04-14 02:21:53
只能等待异步(用async def定义)函数。整个想法是,这样的函数是以特殊的方式编写的,这使得可以在不阻塞事件循环的情况下运行(await)它们。
如果你想从常用的(用def定义的)函数中得到结果,而这个函数需要相当长的执行时间,你可以选择以下几种方法:
将整个函数重写为在另一个线程中对此函数执行asynchronous
通常你会选择第二个选项。
下面是如何做到这一点的示例:
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()请阅读this answer了解asyncio是如何工作的。我想这对你会有很大帮助的。
发布于 2019-01-14 08:50:04
因为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助手函数。
发布于 2022-01-06 13:38:51
您无需等待哪个函数正在异步运行
async def getData():
retrienveData = thirdPartyAPIWrapper.data()
return retrieveDatahttps://stackoverflow.com/questions/49822552
复制相似问题