Path: blob/master/languages/python/asyncio_examples/aiohttp_client.py
1240 views
import asyncio12from contextlib import closing34import time56import aiohttp789async def fetch_page(session, host, port=8000, wait=0):10url = '{}:{}/{}'.format(host, port, wait)11with aiohttp.Timeout(10):12async with session.get(url) as response:13assert response.status == 20014return await response.text()151617def get_multiple_pages(host, waits, port=8000, show_time=True):18tasks = []19pages = []20start = time.perf_counter()2122with closing(asyncio.get_event_loop()) as loop:23with aiohttp.ClientSession(loop=loop) as session:24for wait in waits:25tasks.append(fetch_page(session, host, port, wait))26pages = loop.run_until_complete(asyncio.gather(*tasks))2728duration = time.perf_counter() - start29sum_waits = sum(waits)30if show_time:31msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."32print((msg.format(duration, sum_waits)))33return pages3435if __name__ == '__main__':36def main():37"""Test it."""38pages = get_multiple_pages(host='http://localhost',39port='8888',40waits=[1, 5, 3, 2])41for page in pages:42print(page)43main()444546