Skip to content

Commit 4f7972e

Browse files
committed
async
1 parent c3e9745 commit 4f7972e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

async/aiohttp-get/main.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import aiohttp
2+
import asyncio
3+
import json
4+
5+
async def fetch(session, url):
6+
async with session.get(url) as response:
7+
return await response.text()
8+
9+
async def main(urls):
10+
tasks = []
11+
results = []
12+
async with aiohttp.ClientSession() as session:
13+
for url in urls:
14+
tasks.append(fetch(session, url))
15+
results = await asyncio.gather(*tasks)
16+
return results
17+
18+
def parallel(urls):
19+
loop = asyncio.get_event_loop()
20+
results = loop.run_until_complete(main(urls))
21+
return results
22+
23+
# --- main ---
24+
25+
urls = [
26+
#('https://stackoverflow.com/', 1), # wrong
27+
'https://stackoverflow.com/', # wrong
28+
'https://httpbin.org/',
29+
'http://toscrape.com/',
30+
]
31+
32+
result = parallel(urls)
33+
34+
for item in result:
35+
print(item[:300])
36+
print('-----')
37+
38+

0 commit comments

Comments
 (0)