Sitemap generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.3 KiB

4 years ago
4 years ago
  1. #!/usr/bin/env python3
  2. import time
  3. import asyncio
  4. from aiohttp import ClientSession
  5. class Knocker(object):
  6. def __init__(self, urls=None, sleep_time=.5):
  7. self.urls = urls or []
  8. self.sleep_time = float(sleep_time)
  9. async def fetch(self, url, session):
  10. async with session.get(url) as response:
  11. await asyncio.sleep(self.sleep_time)
  12. status = response.status
  13. date = response.headers.get("DATE")
  14. print("{}:{} with status {}".format(date, response.url, status))
  15. return url, status
  16. async def bound_fetch(self, sem, url, session):
  17. # Getter function with semaphore.
  18. async with sem:
  19. await self.fetch(url, session)
  20. async def run(self):
  21. tasks = []
  22. # create instance of Semaphore
  23. sem = asyncio.Semaphore(20)
  24. # Create client session that will ensure we dont open new connection
  25. # per each request.
  26. async with ClientSession() as session:
  27. for url in self.urls:
  28. # pass Semaphore and session to every GET request
  29. task = asyncio.ensure_future(self.bound_fetch(sem, url, session))
  30. tasks.append(task)
  31. responses = asyncio.gather(*tasks)
  32. await responses