简体   繁体   English

为什么这个 python aiohttp 请求代码不异步运行?

[英]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.

相关问题 为什么此异步信号量实现不能与 python 中的 aiohttp 一起使用 - Why doesn't this asyncio semaphore implementation work with aiohttp in python Python-aiohttp-为什么我的测试无法运行? - Python - aiohttp - Why won't my tests run? 为什么带有 aiohttp 服务器的 websocket 不起作用 - Why websocket with aiohttp server doesn't work 为什么 aiohttp 比 run_in_executor 包裹的请求慢? - Why aiohttp works slower than requests wrapped by run_in_executor? Python属性:为什么此代码不运行该函数? - Python properties: why doesn't this code run the function? 这两个 python 异步代码示例有什么区别? 我试图理解为什么使用 aiohttp 而不是请求 - what is the difference between these two python asyncio code samples? i'm trying to understand why aiohttp is used rather than requests 使用 Python 和 Aiohttp 链接请求 - Chaining Requests using Python and Aiohttp VS 代码 [python] 无法正常运行 - VS code [python] doesn't run properly 在返回 `send_file` 的 flask function 中,代码似乎不会在后续请求中运行,但文件仍在下载。 为什么? - In a flask function which returns `send_file`, the code doesn't appear to run on subsequent requests, yet the file still downloads. Why? Python代码无法与[input]一起运行 - Python code doesn't run with [input]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM