SsdbClient.py 2.8 KB

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