SsdbClient.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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, value):
  46. """
  47. put an item
  48. 将代理放入hash, 使用changeTable指定hash name
  49. :param value:
  50. :return:
  51. """
  52. value = json.dump(value, ensure_ascii=False).encode('utf-8') if isinstance(value, (dict, list)) else value
  53. return self.__conn.hset(self.name, value, None)
  54. def pop(self):
  55. """
  56. pop an item
  57. 弹出一个代理, 使用changeTable指定hash name
  58. :return:
  59. """
  60. key = self.get()
  61. if key:
  62. self.__conn.hdel(self.name, key)
  63. return key
  64. def delete(self, key):
  65. """
  66. Remove the ``key`` from hash ``name``
  67. :param key:
  68. :return:
  69. """
  70. self.__conn.hdel(self.name, key)
  71. def getAll(self):
  72. return self.__conn.hgetall(self.name).keys()
  73. def get_status(self):
  74. """
  75. Return the number of elements in hash ``name``
  76. :return:
  77. """
  78. return self.__conn.hsize(self.name)
  79. def changeTable(self, name):
  80. self.name = name