-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathchained.py
More file actions
45 lines (35 loc) · 1.15 KB
/
chained.py
File metadata and controls
45 lines (35 loc) · 1.15 KB
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
43
44
45
import asyncio
import random
import time
async def main():
user_ids = [1, 2, 3]
start = time.perf_counter()
await asyncio.gather(
*(get_user_with_posts(user_id) for user_id in user_ids)
)
end = time.perf_counter()
print(f"\n==> Total time: {end - start:.2f} seconds")
async def get_user_with_posts(user_id):
user = await fetch_user(user_id)
await fetch_posts(user)
async def fetch_user(user_id):
delay = random.uniform(0.5, 2.0)
print(f"User coro: fetching user by {user_id=}...")
await asyncio.sleep(delay)
user = {"id": user_id, "name": f"User{user_id}"}
print(f"User coro: fetched user with {user_id=} (done in {delay:.1f}s).")
return user
async def fetch_posts(user):
delay = random.uniform(0.5, 2.0)
print(f"Post coro: retrieving posts for {user['name']}...")
await asyncio.sleep(delay)
posts = [f"Post {i} by {user['name']}" for i in range(1, 3)]
print(
f"Post coro: got {len(posts)} posts by {user['name']}"
f" (done in {delay:.1f}s):"
)
for post in posts:
print(f" - {post}")
if __name__ == "__main__":
random.seed(444)
asyncio.run(main())