Blame view

2_chaining_with_await.py 947 Bytes
444c887a   Lars Tiede   first commit
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
  #!/usr/bin/env python
  import asyncio
  import aiohttp
  
  async def get_page(url):
      try:
          print("get {}".format(url))
          response = await aiohttp.get(url)
          print("got {}".format(url))
          return await response.text()
  
      except aiohttp.errors.ClientError as e:
          print("error getting {}: {}".format(url, e))
          return ""
  
  
  async def text_length(url):
      text = await get_page(url)
      return len(text)
  
  
  async def text_lengths(urls):
      lengths = await asyncio.gather(*[
          text_length(url) for url in urls
          ])
      for u, l in zip(urls, lengths):
          print("{}: {} bytes text".format(u, l))
  
  
  urls = [
          "https://www.uit.no",
          "https://www.uio.no",
          "https://www.uib.no",
          "https://www.ntnu.no",
          "http://utviklerlunsj.uit.no",
          "https://www.ihopethisdoesntexist.no/",
          ]
  loop = asyncio.get_event_loop()
  loop.run_until_complete(text_lengths(urls))