如何*正确*在循环中运行 asyncio/aiohttp 请求?

Def*_*or6 3 python asynchronous python-requests python-asyncio aiohttp

我试图同时请求一堆 URL,但 URL 是从列表构建的。目前,我正在循环列表并(我认为)将它们添加到队列中。它肯定比 requests.get 快 10 倍,但是我不确定我是否正确执行,因此可以对其进行优化。我对其进行了分析,发现在并发请求完成后,90% 的时间它仍然处于锁定状态,即开始 -> 10+ 并发请求 -> 锁定 5 秒左右 -> 完成

Unclosed client session此外,此代码最后会生成一条消息。知道为什么吗?很确定这是正确使用上下文管理器。

我已经搜索过但没有找到这个确切的问题

 import signal
 import sys
 import asyncio
 import aiohttp
 import json
 import requests

 lists = ['eth', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo']

 loop = asyncio.get_event_loop()
 client = aiohttp.ClientSession(loop=loop)

 async def fetch(client, url):
     async with client.get(url) as resp:
         assert resp.status == 200
         return await resp.text()

 async def main(loop=loop, url=None):
     async with aiohttp.ClientSession(loop=loop) as client:
         html = await fetch(client, url)
         print(html)

 def signal_handler(signal, frame):
     loop.stop()
     client.close()
     sys.exit(0)

 signal.signal(signal.SIGINT, signal_handler)
 tasks = []
 for item in lists:
     url = "{url}/{endpoint}/{coin_name}".format(
                     url='https://coincap.io',
                     endpoint='page',
                     coin_name=item.upper()
                 )
     print(url)
     tasks.append(
         asyncio.ensure_future(main(url=url))
     )

 loop.run_until_complete(asyncio.gather(*tasks))
Run Code Online (Sandbox Code Playgroud)

SCo*_*vin 8

看起来你所做的工作是有效的,但正如你所认为的那样,你并没有完全正确地完成所有事情:

  • 您创建了一个从未使用过的客户端,并且没有正确关闭(导致Unclosed client session)警告
  • 您为每个请求创建一个客户端,这比重用客户端的效率要低得多。
  • 您没有在正在运行的事件循环中运行大部分代码。
  • 如果您有长时间运行的异步任务,您可能需要使用信号处理程序,则没有必要add_signal_handler

这是我对您的代码的简化处理:

import asyncio
import aiohttp

lists = ['eth', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo']


async def fetch(client, item):
    url = 'https://coincap.io/{endpoint}/{coin_name}'.format(
        endpoint='page',
        coin_name=item.upper()
    )
    async with client.get(url) as resp:
        assert resp.status == 200
        html = await resp.text()
        print(html)


async def main():
    async with aiohttp.ClientSession() as client:
        await asyncio.gather(*[
            asyncio.ensure_future(fetch(client, item))
            for item in lists
        ])


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)

如果您想处理 html,您可以在 fetch 协程中执行此操作,也可以对gather.

  • 但在这里你不需要它 - `asyncio.gather(*(fetch(client, item) for item inlists))` 应该可以正常工作。`gather` [明确记录](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) 接受协程或 future。 (2认同)