【问题标题】:HEAD requests with aiohttp is dog slow使用 aiohttp 的 HEAD 请求很慢
【发布时间】:2019-03-19 22:37:14
【问题描述】:

给定一个包含 50k 个网站 url 的列表,我的任务是找出其中哪些是可用的/可访问的。这个想法只是向每个 URL 发送一个HEAD 请求并查看状态响应。据我所知,异步方法是可行的方法,现在我使用asyncioaiohttp

我想出了以下代码,但速度非常糟糕。在我的 10mbit 连接上,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

【问题讨论】:

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


    【解决方案1】:

    现在您正在一次启动所有请求。因此,瓶颈可能出现在某处。为避免这种情况,可以使用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 秒。

    还有很多事情可以做:

    • 你应该发挥信号量值来获得更好的性能 适合您的具体环境和任务。

    • 尝试将超时时间从 20 降低到,比如说,5 秒:因为你只是在做头部请求,所以不需要太多 时间。如果请求挂起 5 秒,则很有可能不会 完全成功。

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

    • 顺便问一下,你安装了aiodns(正如doc 建议的那样)吗?

    • disabling ssl 有什么改变吗?

    • 尝试启用logging的调试级别,看看那里是否有任何有用的信息

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

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

    【讨论】:

    • 鉴于单个线程上只有一个事件循环,是不是使用 200 的信号量与仅使用 aiohttp.TCPConnector(limit=200) 初始化相同?我在轮询 httbin 时获得 60 个 URL/秒,这虽然很低,但我想在范围内,但是在使用我自己的数据时,10 个 URL/秒(从 5/秒上升,因为我也使用sock_read=20 timeout)。我不明白如果我同时启动所有请求,为什么会有区别。我已经尝试过上述限制,并且在给定 1K URL 列表的情况下,200 和 1K 之间没有显着差异。
    • 补充一点,我的系统没有很大的负载。 CPU 内核保持在 20% 以下;没有使用内存,上/下网络速度低于 70kb/s。我尝试将sock_readsock_connect 从 20 秒降低到 5,但我自己的 URL 上的速度完全相同,大约 10/秒,而 httpbin 大约 120/秒。所以 httbin 对较低的超时做出反应,但我的数据(有很多不同的错误,例如 404、由对等方重置、无法访问、禁止、你有什么)没有。
    • is not using a semaphore of 200 the same as just initializing with aiohttp.TCPConnector(limit=200)? - 不能肯定地说,但直觉说最好不要在我们想要之前启动请求,而不是在底层 aiohttp 连接池上中继。例如,当 DNS 解析超时开始时没有信号量 - 当 session.head 被调用或连接实际可用时?使用信号量,您可以确定是否不会太早开始。 |||我还更新了答案,您可以尝试更多选项。
    • 这是一个非常有趣的问题。我看了看代码。您不应该从 CSV 或文本文件中读取 URL 列表吗?我看不到任何扫描 URL 扫描列表的方法。这是怎么做的?谢谢。
    • @asher url 是纯字符串,不应该 take too much RAM 除非你有数十亿个。但如果是这种情况,那么是的,您应该按需从存储中读取它们。我想说 DB 最适合,asyncio has some drivers。使用 aiofiles 包装器可以从 CSV 或其他文件中读取,但它会比 DB 更复杂且效率更低。
    猜你喜欢
    • 2013-03-24
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2018-06-28
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多