亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 異步響應時間

Python 異步響應時間

慕村9548890 2024-01-12 10:40:09
我正在嘗試學習 asyncio 和 aiohttp。我有以下代碼來使用 asyncio 查詢一堆 URL。import aiohttpimport asynciosync 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())如何獲取每個異步查詢的響應時間?我的第一個想法是只使用計時器,但我不知道在這種情況下如何使用它。我嘗試搜索是否有人做過類似的事情,但找不到任何東西。
查看完整描述

1 回答

?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

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)


查看完整回答
反對 回復 2024-01-12
  • 1 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號