tester.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import asyncio
  2. import aiohttp
  3. from loguru import logger
  4. from proxypool.schemas import Proxy
  5. from proxypool.storages.redis import RedisClient
  6. from proxypool.setting import TEST_TIMEOUT, TEST_BATCH, TEST_URL, TEST_VALID_STATUS
  7. from aiohttp import ClientProxyConnectionError, ServerDisconnectedError, ClientOSError
  8. from asyncio import TimeoutError
  9. EXCEPTIONS = (
  10. ClientProxyConnectionError,
  11. ConnectionRefusedError,
  12. TimeoutError,
  13. ServerDisconnectedError,
  14. ClientOSError
  15. )
  16. class Tester(object):
  17. """
  18. tester for testing proxies in queue
  19. """
  20. def __init__(self):
  21. """
  22. init redis
  23. """
  24. self.redis = RedisClient()
  25. self.loop = asyncio.get_event_loop()
  26. async def test(self, proxy: Proxy):
  27. """
  28. test single proxy
  29. :param proxy: Proxy object
  30. :return:
  31. """
  32. async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
  33. try:
  34. logger.debug(f'testing {proxy.string()}')
  35. async with session.get(TEST_URL, proxy=f'http://{proxy.string()}', timeout=TEST_TIMEOUT,
  36. allow_redirects=False) as response:
  37. if response.status in TEST_VALID_STATUS:
  38. self.redis.max(proxy)
  39. logger.debug(f'proxy {proxy.string()} is valid, set max score')
  40. else:
  41. self.redis.decrease(proxy)
  42. logger.debug(f'proxy {proxy.string()} is invalid, decrease score')
  43. except EXCEPTIONS:
  44. self.redis.decrease(proxy)
  45. logger.debug(f'proxy {proxy.string()} is invalid, decrease score')
  46. @logger.catch
  47. def run(self):
  48. """
  49. test main method
  50. :return:
  51. """
  52. # event loop of aiohttp
  53. logger.info('stating tester...')
  54. count = self.redis.count()
  55. logger.debug(f'{count} proxies to test')
  56. for i in range(0, count, TEST_BATCH):
  57. # start end end offset
  58. start, end = i, min(i + TEST_BATCH, count)
  59. logger.debug(f'testing proxies from {start} to {end} indices')
  60. proxies = self.redis.batch(start, end)
  61. tasks = [self.test(proxy) for proxy in proxies]
  62. # run tasks using event loop
  63. self.loop.run_until_complete(asyncio.wait(tasks))
  64. if __name__ == '__main__':
  65. tester = Tester()
  66. tester.run()