SsdbClient.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. """
  4. -------------------------------------------------
  5. File Name: SsdbClient.py
  6. Description : 封装SSDB操作
  7. Author : JHao
  8. date: 2016/12/2
  9. -------------------------------------------------
  10. Change Activity:
  11. 2016/12/2:
  12. 2017/09/22: PY3中 redis-py返回的数据是bytes型
  13. -------------------------------------------------
  14. """
  15. __author__ = 'JHao'
  16. from Util import EnvUtil
  17. from redis.connection import BlockingConnectionPool
  18. from redis import Redis
  19. import random
  20. class SsdbClient(object):
  21. """
  22. SSDB client
  23. SSDB中代理存放的容器为hash:
  24. 原始代理存放在name为raw_proxy的hash中,key为代理的ip:port,value为为None,以后扩展可能会加入代理属性;
  25. 验证后的代理存放在name为useful_proxy的hash中,key为代理的ip:port,value为一个计数,初始为1,每校验失败一次减1;
  26. """
  27. def __init__(self, name, host, port):
  28. """
  29. init
  30. :param name: hash name
  31. :param host: ssdb host
  32. :param port: ssdb port
  33. :return:
  34. """
  35. self.name = name
  36. self.__conn = Redis(connection_pool=BlockingConnectionPool(host=host, port=port))
  37. def get(self, proxy):
  38. """
  39. get an item
  40. 从hash中获取对应的proxy, 使用前需要调用changeTable()
  41. :param proxy:
  42. :return:
  43. """
  44. data = self.__conn.hget(name=self.name, key=proxy)
  45. if data:
  46. return data.decode('utf-8') if EnvUtil.PY3 else data
  47. else:
  48. return None
  49. def put(self, proxy, num=1):
  50. """
  51. 将代理放入hash, 使用changeTable指定hash name
  52. :param proxy:
  53. :param num:
  54. :return:
  55. """
  56. data = self.__conn.hincrby(self.name, proxy, num)
  57. return data
  58. def delete(self, key):
  59. """
  60. Remove the ``key`` from hash ``name``
  61. :param key:
  62. :return:
  63. """
  64. self.__conn.hdel(self.name, key)
  65. def update(self, key, value):
  66. self.__conn.hincrby(self.name, key, value)
  67. def pop(self):
  68. proxies = self.__conn.hkeys(self.name)
  69. if proxies:
  70. proxy = random.choice(proxies)
  71. self.delete(proxy)
  72. return proxy
  73. return None
  74. def exists(self, key):
  75. return self.__conn.hexists(self.name, key)
  76. def getAll(self):
  77. item_dict = self.__conn.hgetall(self.name)
  78. if EnvUtil.PY3:
  79. return {key.decode('utf8'): value.decode('utf8') for key, value in item_dict.items()}
  80. else:
  81. return item_dict
  82. def getNumber(self):
  83. """
  84. Return the number of elements in hash ``name``
  85. :return:
  86. """
  87. return self.__conn.hlen(self.name)
  88. def changeTable(self, name):
  89. self.name = name