Python 异步响应时间

我正在尝试学习 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())

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


慕村9548890
浏览 87回答 1
1回答

POPMUISE

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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python