【问题标题】:Python asyncio response timePython异步响应时间
【发布时间】:2020-10-31 07:02:18
【问题描述】:

我正在尝试学习 asyncio 和 aiohttp。我有以下代码可以使用 asyncio 查询一堆 URL。

import aiohttp
import asyncio

sync def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
            'http://yahoo.com',
            'https://google.com',
            'http://bing.com'
        ]
    tasks = []
    async with aiohttp.ClientSession() as session:
        for url in urls:
            tasks.append(fetch(session, url))
        htmls = await asyncio.gather(*tasks)
        for html in htmls:
            print(html[:100] + "\n")
    
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

如何获取每个异步查询的响应时间?我的第一个想法是只使用一个计时器,但我不知道如何在这种情况下使用它。我试过搜索是否有人做过类似的事情,但找不到任何东西。

【问题讨论】:

  • 可以记录开始请求前的时间,计算请求完成时的时间差,并与HTML内容一起返回。

标签: python python-asyncio aiohttp


【解决方案1】:
async def fetch(session, url):
    """[Coroutine to send HTTP request to URLs provided]

    Args:
        session ([aiohttp Client Session object]): [session object]
        url ([string]): [URL to query]

    Returns:
        [list]: [response url, status and time taken]
    """
    tic = time.perf_counter() # Start timer
    try:
        response = await session.request(method='GET', url=url, timeout=10)
        toc = time.perf_counter() # Stop timer
        time_taken  = toc - tic # Calculate time taken to get response
        response.raise_for_status()
        print("URL : ", url)
        print("HTTP Status : ", response.status)
        print(f"Time taken : {time_taken:4f} seconds")
        print()
        return str(response.url), response.status, time_taken
    
    except HTTPError as http_err:
        logging.error(http_err)
    except Exception as err:
        logging.error(err)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2011-09-03
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多