SsdbClient.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. """
  3. -------------------------------------------------
  4. File Name: SsdbClient.py
  5. Description : 封装SSDB操作
  6. Author : JHao
  7. date: 2016/12/2
  8. -------------------------------------------------
  9. Change Activity:
  10. 2016/12/2:
  11. -------------------------------------------------
  12. """
  13. __author__ = 'JHao'
  14. from ssdb.connection import BlockingConnectionPool
  15. from ssdb import SSDB
  16. import random
  17. import json
  18. class SsdbClient(object):
  19. """
  20. SSDB client
  21. """
  22. def __init__(self, name, host, port):
  23. """
  24. init
  25. :param name:
  26. :param host:
  27. :param port:
  28. :return:
  29. """
  30. self.name = name
  31. self.__conn = SSDB(connection_pool=BlockingConnectionPool(host=host, port=port))
  32. def get(self):
  33. """
  34. get an item
  35. :return:
  36. """
  37. values = self.__conn.hgetall(name=self.name)
  38. return random.choice(values.keys()) if values else None
  39. def put(self, value):
  40. """
  41. put an item
  42. :param value:
  43. :return:
  44. """
  45. value = json.dump(value, ensure_ascii=False).encode('utf-8') if isinstance(value, (dict, list)) else value
  46. return self.__conn.hset(self.name, value, None)
  47. def pop(self):
  48. """
  49. pop an item
  50. :return:
  51. """
  52. key = self.get()
  53. if key:
  54. self.__conn.hdel(self.name, key)
  55. return key
  56. def delete(self, key):
  57. """
  58. delete an item
  59. :param key:
  60. :return:
  61. """
  62. self.__conn.hdel(self.name, key)
  63. def getAll(self):
  64. return self.__conn.hgetall(self.name).keys()
  65. def changeTable(self, name):
  66. self.name = name