SsdbClient.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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/04/26: 添加get_status方法获取hash长度
  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. import json
  21. class SsdbClient(object):
  22. """
  23. SSDB client
  24. SSDB中代理存放的容器为hash:
  25. 原始代理存放在name为raw_proxy的hash中,key为代理的ip:port,value为None,以后扩展可能会加入代理属性;
  26. 验证后供flask使用的代理存放在name为useful_proxy的hash中,key为代理的ip:port,value为None,以后扩展可能会加入代理属性;
  27. """
  28. def __init__(self, name, host, port):
  29. """
  30. init
  31. :param name: hash name
  32. :param host: ssdb host
  33. :param port: ssdb port
  34. :return:
  35. """
  36. self.name = name
  37. self.__conn = Redis(connection_pool=BlockingConnectionPool(host=host, port=port))
  38. def get(self):
  39. """
  40. get an item
  41. 从useful_proxy_queue随机获取一个可用代理, 使用前需要调用changeTable("useful_proxy_queue")
  42. :return:
  43. """
  44. values = self.__conn.hkeys(name=self.name)
  45. keys = list(values) if EnvUtil.PY3 else values
  46. return random.choice(keys) if values else None
  47. def put(self, key):
  48. """
  49. put an item
  50. 将代理放入hash, 使用changeTable指定hash name
  51. :param key:
  52. :return:
  53. """
  54. key = json.dump(key, ensure_ascii=False) if isinstance(key, (dict, list)) else key
  55. return self.__conn.hincrby(self.name, key, 1)
  56. def getvalue(self, key):
  57. value = self.__conn.hget(self.name, key)
  58. return value if value else None
  59. def pop(self):
  60. """
  61. pop an item
  62. 弹出一个代理, 使用changeTable指定hash name
  63. :return:
  64. """
  65. key = self.get()
  66. if key:
  67. self.__conn.hdel(self.name, key)
  68. return key
  69. def delete(self, key):
  70. """
  71. Remove the ``key`` from hash ``name``
  72. :param key:
  73. :return:
  74. """
  75. self.__conn.hdel(self.name, key)
  76. def inckey(self, key, value):
  77. self.__conn.hincrby(self.name, key, value)
  78. def getAll(self):
  79. keys = self.__conn.hkeys(self.name)
  80. return list(keys) if EnvUtil.PY3 else keys
  81. def get_status(self):
  82. """
  83. Return the number of elements in hash ``name``
  84. :return:
  85. """
  86. return self.__conn.hlen(self.name)
  87. def changeTable(self, name):
  88. self.name = name