python - 如何在Python中结契约(Contract)步对象迭代​​和异步代码?

标签 python python-asyncio aiohttp

我有一个对象列表,对于每个对象,我需要对其进行一些异步工作。我不确定我的构造是否正确:

def run(tasks):
    async def async_wrapper():
        async def update_task():
            updated_task = await task_manager.async_get_task_status(session, task)
            # do some works with updated_task

        workers = []
        resolver = aiohttp.AsyncResolver()
        connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
        async with aiohttp.ClientSession(connector=connector) as session:
            for local_task in tasks: # tasks is a list of object
                await update_ocr_task()

    loop = asyncio.get_event_loop()
    loop.run_until_complete(aysnc_wrapper())

我认为 for 循环是同步的,并且会完全阻止进度,对吗?如果是的话,如何构建它?

最佳答案

def run(tasks):
    # ...

    loop = asyncio.get_event_loop()
    loop.run_until_complete(aysnc_wrapper())

通常这不是人们编写异步程序的方式:事件循环应该是全局的,并作为整个脚本的主要入口点启动。像您一样执行操作(在单个函数 run 内运行事件循环)会使上层代码无法在同一事件循环中运行其他协程。

如果您了解这一点,并且您想要的只是阻止不能与其他异步内容一起使用的 run 函数,请进一步阅读。


async_wrapper 的问题在于,它仅在前一个协程完成后才等待下一个 update_ocr_task() 协程。 For 循环并不是我们所说的“阻塞”,但它只是不是并发的 - 它没有利用异步范例提供的好处。

要实现使用 asyncio 的好处,您应该同时运行多个协程。常见的方法是使用 asyncio.gather() :

async def async_wrapper():

    async def process_single_task(task):
        resolver = aiohttp.AsyncResolver()
        connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
        async with aiohttp.ClientSession(connector=connector) as session:
            await session.get(...) # do all job for *single* local task here.

    # Run multiple task processing coroutines concurrently:
    await asyncio.gather(
        *[process_single_task(t) for t in tasks]
    )

如果您愿意,您还可以阅读this一般而言,关于 asyncio 的答案很少。

关于python - 如何在Python中结契约(Contract)步对象迭代​​和异步代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47706580/

相关文章:

python - 如何让 uvicorn 运行异步构建的应用程序?

python-3.x - os.kill 与 process.terminate 在 aiohttp 中

python - 一段时间后 Discord api websocket 网关连接断开

Python Psycopg2 cursor.execute 返回 None

python - SSL : CERTIFICATE_VERIFY_FAILED error when curator access elasticsearch

python - 在Django中自动导入自定义文件

python - 没有错误记录失败的 Postgres/Psycopg2 copy_from

python - 在 asyncio(和观察者模式)中链接协程

python-3.x - 可视化 asyncio 协程执行

python-3.x - 为什么我们不能使用 aiohttp 为生产提供静态文件?