-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathanimals_asyncio.py
More file actions
34 lines (22 loc) · 777 Bytes
/
animals_asyncio.py
File metadata and controls
34 lines (22 loc) · 777 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
import asyncio
import aiohttp
BASE_URL = 'https://ericappelt.com/animals/'
async def speak(animal, session):
async with session.get('{}/{}'.format(BASE_URL, animal)) as response:
response.raise_for_status()
sound = await response.text()
return 'The {} says "{}".'.format(animal, sound)
async def main():
animals = ['cow', 'pig', 'chicken']
coroutines = []
async with aiohttp.ClientSession() as session:
for animal in animals:
coro = speak(animal, session)
coroutines.append(coro)
responses = await asyncio.gather(*coroutines)
for line in responses:
print(line)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()