SsdbClient.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. -------------------------------------------------
  13. """
  14. __author__ = 'JHao'
  15. from ssdb.connection import BlockingConnectionPool
  16. from ssdb import SSDB
  17. import random
  18. import json
  19. class SsdbClient(object):
  20. """
  21. SSDB client
  22. SSDB中代理存放的容器为hash:
  23. 原始代理存放在name为raw_proxy的hash中,key为代理的ip:port,value为None,以后扩展可能会加入代理属性;
  24. 验证后供flask使用的代理存放在name为useful_proxy_queue的hash中,key为代理的ip:port,value为None,以后扩展可能会加入代理属性;
  25. """
  26. def __init__(self, name, host, port):
  27. """
  28. init
  29. :param name: hash name
  30. :param host: ssdb host
  31. :param port: ssdb port
  32. :return:
  33. """
  34. self.name = name
  35. self.__conn = SSDB(connection_pool=BlockingConnectionPool(host=host, port=port))
  36. def get(self):
  37. """
  38. get an item
  39. 从useful_proxy_queue随机获取一个可用代理, 使用前需要调用changeTable("useful_proxy_queue")
  40. :return:
  41. """
  42. values = self.__conn.hgetall(name=self.name)
  43. return random.choice(values.keys()) if values else None
  44. def put(self, value):
  45. """
  46. put an item
  47. 将代理放入hash, 使用changeTable指定hash name
  48. :param value:
  49. :return:
  50. """
  51. value = json.dump(value, ensure_ascii=False).encode('utf-8') if isinstance(value, (dict, list)) else value
  52. return self.__conn.hset(self.name, value, None)
  53. def pop(self):
  54. """
  55. pop an item
  56. 弹出一个代理, 使用changeTable指定hash name
  57. :return:
  58. """
  59. key = self.get()
  60. if key:
  61. self.__conn.hdel(self.name, key)
  62. return key
  63. def delete(self, key):
  64. """
  65. delete an item
  66. :param key:
  67. :return:
  68. """
  69. self.__conn.hdel(self.name, key)
  70. def getAll(self):
  71. return self.__conn.hgetall(self.name).keys()
  72. def changeTable(self, name):
  73. self.name = name