/
part_12.py
42 lines (33 loc) · 1.05 KB
/
part_12.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
Concurrency - Async - asyncio.gather (with aiohttp)
"""
import asyncio
import requests
from aiohttp import ClientSession
print(__doc__)
loop = asyncio.get_event_loop()
run = loop.run_until_complete
async def a_http_get(session, delay):
print(f"Task {delay} start")
response = await session.get(f"http://localhost:8000/count?delay={delay}")
v = await response.json()
print(f"Task {delay} end")
return v
async def http_get(delay):
print(f"Task {delay} start")
response = requests.get(f"http://localhost:8000/count?delay={delay}")
print(f"Task {delay} end")
return response.json()
if __name__ == "__main__":
# create_task creates asyncio.Task and schedules it on the event loop
session = ClientSession()
values = run(asyncio.gather(*(
a_http_get(session, i) for i in range(5)
)))
run(session.close())
print(values)
# this blocks the event loop, and nothing runs concurrently
values = loop.run_until_complete(asyncio.gather(*(
http_get(i) for i in range(5)
)))
print(values)