与aiohttp的HEAD请求太慢了

时间:2019-03-19 22:37:14

标签: python python-3.x python-asyncio aiohttp

给定一个50k网站网址的列表,我受命找出其中哪些网址可以访问。这个想法只是向每个URL发送一个HEAD请求,并查看状态响应。据我所知,异步方法是行之有效的方法,现在我将asyncioaiohttp结合使用。

我想出了以下代码,但是速度非常糟糕。在10兆位连接上,使用1000个URL大约需要200秒。我不知道会有什么速度,但是我是Python异步编程的新手,所以我觉得自己在某个地方犯了错误。如您所见,我尝试将允许的并发连接数增加到1000(从默认的100)增加,并且将DNS解析的持续时间保留在缓存中。都没有太大效果。该环境具有Python 3.6和aiohttp 3.5.4。

也欢迎与问题无关的代码审查。

import asyncio
import time
from socket import gaierror
from typing import List, Tuple

import aiohttp
from aiohttp.client_exceptions import TooManyRedirects

# Using a non-default user-agent seems to avoid lots of 403 (Forbidden) errors
HEADERS = {
    'user-agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) '
                   'AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/45.0.2454.101 Safari/537.36'),
}


async def get_status_code(session: aiohttp.ClientSession, url: str) -> Tuple[int, str]:
    try:
        # A HEAD request is quicker than a GET request
        resp = await session.head(url, allow_redirects=True, ssl=False, headers=HEADERS)
        async with resp:
            status = resp.status
            reason = resp.reason
        if status == 405:
            # HEAD request not allowed, fall back on GET
            resp = await session.get(
                url, allow_redirects=True, ssl=False, headers=HEADERS)
            async with resp:
                status = resp.status
                reason = resp.reason
        return (status, reason)
    except aiohttp.InvalidURL as e:
        return (900, str(e))
    except aiohttp.ClientConnectorError:
        return (901, "Unreachable")
    except gaierror as e:
        return (902, str(e))
    except aiohttp.ServerDisconnectedError as e:
        return (903, str(e))
    except aiohttp.ClientOSError as e:
        return (904, str(e))
    except TooManyRedirects as e:
        return (905, str(e))
    except aiohttp.ClientResponseError as e:
        return (906, str(e))
    except aiohttp.ServerTimeoutError:
        return (907, "Connection timeout")
    except asyncio.TimeoutError:
        return (908, "Connection timeout")


async def get_status_codes(loop: asyncio.events.AbstractEventLoop, urls: List[str],
                           timeout: int) -> List[Tuple[int, str]]:
    conn = aiohttp.TCPConnector(limit=1000, ttl_dns_cache=300)
    client_timeout = aiohttp.ClientTimeout(connect=timeout)
    async with aiohttp.ClientSession(
            loop=loop, timeout=client_timeout, connector=conn) as session:
        codes = await asyncio.gather(*(get_status_code(session, url) for url in urls))
        return codes


def poll_urls(urls: List[str], timeout=20) -> List[Tuple[int, str]]:
    """
    :param timeout: in seconds
    """
    print("Started polling")
    time1 = time.time()
    loop = asyncio.get_event_loop()
    codes = loop.run_until_complete(get_status_codes(loop, urls, timeout))
    time2 = time.time()
    dt = time2 - time1
    print(f"Polled {len(urls)} websites in {dt:.1f} seconds "
          f"at {len(urls)/dt:.3f} URLs/sec")
    return codes

1 个答案:

答案 0 :(得分:3)

现在,您可以一次启动所有请求。因此,瓶颈可能出现在某个地方。为了避免这种情况,可以使用semaphore

# code

sem = asyncio.Semaphore(200)


async def get_status_code(session: aiohttp.ClientSession, url: str) -> Tuple[int, str]:
    try:
        async with sem:
            resp = await session.head(url, allow_redirects=True, ssl=False, headers=HEADERS)
            # code

我通过以下方式对其进行了测试:

poll_urls([
    'http://httpbin.org/delay/1' 
    for _ 
    in range(2000)
])

得到了:

Started polling
Polled 2000 websites in 13.2 seconds at 151.300 URLs/sec

尽管它请求一个主机,但它表明异步方法可以完成此工作:13秒。 <2000秒。

还可以做几件事:

  • 您应该播放信号量值以获得更好的性能 具体的环境和任务。

  • 尝试将超时时间从20降低到5 秒:由于您只是在提出头要求,因此不需要太多时间 时间。如果请求挂起5秒钟,则很有可能不会 完全成功。

  • 在脚本运行时监视系统资源(网络/ CPU / RAM) 可以帮助您找出瓶颈是否仍然存在。

  • 顺便问一下,您是否安装了aiodns(如doc所建议的那样)?

  • disabling ssl会进行任何更改吗?

  • 尝试启用logging的调试级别,以查看是否有有用的信息

  • 尝试设置client tracing,尤其要测量每个请求步骤的时间,以查看哪些请求花费的时间最多

如果没有完全可重复的情况,很难说更多。