SsdbClient.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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())
  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. self.__conn.hdel(self.name, key)
  54. return key
  55. def delete(self, key):
  56. """
  57. delete an item
  58. :param key:
  59. :return:
  60. """
  61. self.__conn.hdel(self.name, key)
  62. def getAll(self):
  63. return self.__conn.hgetall(self.name).keys()
  64. def changeTable(self, name):
  65. self.name = name