[英]Why doesn't this python aiohttp requests code run asynchronously?
I'm trying to access an API with aiohttp but something is causing this code to block each iteration.我正在尝试使用 aiohttp 访问 API 但某些原因导致此代码阻止每次迭代。
def main():
async with aiohttp.ClientSession() as session:
for i, (image, target) in enumerate(dataset_val):
image_bytes = pil_to_bytes(image)
async with session.post('http://localhost:8080/predictions/resnet50', data=image_bytes) as resp:
print(await resp.text())
print(i, flush=True, end='\r')
asyncio.run(main())
As explained by @deceze , await will wait for your result inside your loop.正如@deceze所解释的, await 将在循环中等待您的结果。 If you want to call everything at the same time, you need to call everything from an external loop and gather the results.如果您想同时调用所有内容,则需要从外部循环调用所有内容并收集结果。
Here's a way of doing it这是一种方法
import asyncio
import aiohttp
async def call(session: aiohttp.ClientSession, url: str, image):
image_bytes = pil_to_bytes(image)
async with session.post(url, data=image_bytes) as response:
return await response.text()
async def call_all(url:str, tasks: list):
async with aiohttp.ClientSession() as session:
results = await asyncio.gather(
*[call(session, url, img) for img, target in tasks],
return_exceptions=True
)
return results
loop = asyncio.get_event_loop()
res = loop.run_until_complete(
call_all('http://localhost:8080/predictions/resnet50', dataset_val)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.