proxyHandler.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # -*- coding: utf-8 -*-
  2. """
  3. -------------------------------------------------
  4. File Name: ProxyHandler.py
  5. Description :
  6. Author : JHao
  7. date: 2016/12/3
  8. -------------------------------------------------
  9. Change Activity:
  10. 2016/12/3:
  11. -------------------------------------------------
  12. """
  13. __author__ = 'JHao'
  14. from helper.proxy import Proxy
  15. from db.dbClient import DbClient
  16. from handler.configHandler import ConfigHandler
  17. class ProxyHandler(object):
  18. """ Proxy CRUD operator"""
  19. def __init__(self):
  20. self.conf = ConfigHandler()
  21. self.db = DbClient(self.conf.dbConn)
  22. def get(self):
  23. """
  24. return a useful proxy
  25. :return:
  26. """
  27. self.db.changeTable(self.conf.useProxy)
  28. proxy = self.db.get()
  29. if proxy:
  30. return Proxy.createFromJson(proxy)
  31. return None
  32. def pop(self):
  33. """
  34. return and delete a useful proxy
  35. :return:
  36. """
  37. self.db.changeTable(self.conf.useProxy)
  38. proxy = self.db.pop()
  39. if proxy:
  40. return Proxy.createFromJson(proxy)
  41. return None
  42. def put(self, proxy_obj):
  43. """
  44. put proxy into use proxy
  45. :return:
  46. """
  47. self.db.changeTable(self.conf.useProxy)
  48. self.db.put(proxy_obj)
  49. def delete(self, proxy_str):
  50. """
  51. delete useful proxy
  52. :param proxy_str:
  53. :return:
  54. """
  55. self.db.changeTable(self.conf.useProxy)
  56. return self.db.delete(proxy_str)
  57. def getAll(self):
  58. """
  59. get all proxy from pool as Proxy list
  60. :return:
  61. """
  62. self.db.changeTable(self.conf.useProxy)
  63. proxies_dict = self.db.getAll()
  64. return [Proxy.createFromJson(value) for _, value in proxies_dict.items()]
  65. def exists(self, proxy_str):
  66. """
  67. check proxy exists
  68. :param proxy_str:
  69. :return:
  70. """
  71. self.db.changeTable(self.conf.useProxy)
  72. return self.db.exists(proxy_str)
  73. def getCount(self):
  74. """
  75. return raw_proxy and use_proxy count
  76. :return:
  77. """
  78. self.db.changeTable(self.conf.useProxy)
  79. total_raw_proxy = self.db.getCount()
  80. self.db.changeTable(self.conf.rawProxy)
  81. total_use_proxy = self.db.getCount()
  82. return {'raw_proxy': total_raw_proxy, 'use_proxy': total_use_proxy}