Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/asyncio_examples/aiohttp_client.py
1240 views
1
import asyncio
2
3
from contextlib import closing
4
5
import time
6
7
import aiohttp
8
9
10
async def fetch_page(session, host, port=8000, wait=0):
11
url = '{}:{}/{}'.format(host, port, wait)
12
with aiohttp.Timeout(10):
13
async with session.get(url) as response:
14
assert response.status == 200
15
return await response.text()
16
17
18
def get_multiple_pages(host, waits, port=8000, show_time=True):
19
tasks = []
20
pages = []
21
start = time.perf_counter()
22
23
with closing(asyncio.get_event_loop()) as loop:
24
with aiohttp.ClientSession(loop=loop) as session:
25
for wait in waits:
26
tasks.append(fetch_page(session, host, port, wait))
27
pages = loop.run_until_complete(asyncio.gather(*tasks))
28
29
duration = time.perf_counter() - start
30
sum_waits = sum(waits)
31
if show_time:
32
msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}."
33
print((msg.format(duration, sum_waits)))
34
return pages
35
36
if __name__ == '__main__':
37
def main():
38
"""Test it."""
39
pages = get_multiple_pages(host='http://localhost',
40
port='8888',
41
waits=[1, 5, 3, 2])
42
for page in pages:
43
print(page)
44
main()
45
46