-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathconcurrency.py
More file actions
39 lines (26 loc) · 816 Bytes
/
concurrency.py
File metadata and controls
39 lines (26 loc) · 816 Bytes
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
# Avoid this:
# import asyncio
# import requests
# async def main():
# await asyncio.gather(
# fetch_status("https://example.com"),
# fetch_status("https://python.org"),
# )
# async def fetch_status(url):
# response = requests.get(url) # Blocking I/O task
# return response.status_code
# asyncio.run(main())
# Favor this:
import asyncio
import aiohttp
async def main():
async with aiohttp.ClientSession() as session:
statuses = await asyncio.gather(
fetch_status(session, "https://example.com"),
fetch_status(session, "https://realpython.com"),
)
print(statuses)
async def fetch_status(session, url):
async with session.get(url) as response: # Non-blocking I/O task
return response.status
asyncio.run(main())