1
- """aiohttp-based client to retrieve web pages.
2
- """
1
+ """aiohttp-based client to retrieve web pages."""
3
2
4
- import asyncio
5
- from contextlib import closing
6
3
import time
7
-
4
+ import asyncio
8
5
import aiohttp
9
6
10
7
11
8
async def fetch_page (session , host , port = 8000 , wait = 0 ):
12
- """Get one page.
13
- """
9
+ """Get one page."""
14
10
url = '{}:{}/{}' .format (host , port , wait )
15
11
with aiohttp .Timeout (10 ):
16
12
async with session .get (url ) as response :
17
13
assert response .status == 200
18
- return await response .text ()
14
+ text = await response .text ()
15
+ return text .strip ('\n ' )
19
16
20
17
21
- def get_multiple_pages (host , waits , port = 8000 , show_time = True ):
22
- """Get multiple pages.
23
- """
24
- tasks = []
25
- pages = []
18
+ async def get_multiple_pages (host , waits , port = 8000 , show_time = True ):
19
+ """Get multiple pages."""
26
20
start = time .perf_counter ()
27
- with closing (asyncio .get_event_loop ()) as loop :
28
- with aiohttp .ClientSession () as session :
29
- for wait in waits :
30
- tasks .append (fetch_page (session , host , port , wait ))
31
- pages = loop .run_until_complete (asyncio .gather (* tasks ))
21
+ with aiohttp .ClientSession () as session :
22
+ tasks = [fetch_page (session , host , port , wait ) for wait in waits ]
23
+ pages = await asyncio .gather (* tasks )
32
24
duration = time .perf_counter () - start
33
25
sum_waits = sum (waits )
34
26
if show_time :
@@ -37,14 +29,15 @@ def get_multiple_pages(host, waits, port=8000, show_time=True):
37
29
return pages
38
30
39
31
40
- if __name__ == '__main__' :
32
+ async def main ():
33
+ """Test it."""
34
+ pages = await get_multiple_pages (
35
+ host = 'http://localhost' , port = '8000' , waits = [1 , 5 , 3 , 2 ])
36
+ for page in pages :
37
+ print (page )
41
38
42
- def main ():
43
- """Test it.
44
- """
45
- pages = get_multiple_pages (host = 'http://localhost' , port = '8000' ,
46
- waits = [1 , 5 , 3 , 2 ])
47
- for page in pages :
48
- print (page )
49
39
50
- main ()
40
+ if __name__ == '__main__' :
41
+ loop = asyncio .get_event_loop ()
42
+ loop .run_until_complete (main ())
43
+ loop .close ()
0 commit comments