DbClient.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. """
  4. -------------------------------------------------
  5. File Name: DbClient.py
  6. Description : DB工厂类
  7. Author : JHao
  8. date: 2016/12/2
  9. -------------------------------------------------
  10. Change Activity:
  11. 2016/12/2:
  12. -------------------------------------------------
  13. """
  14. __author__ = 'JHao'
  15. import os
  16. import sys
  17. from Util.GetConfig import GetConfig
  18. from Util.utilClass import Singleton
  19. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  20. class DbClient(object):
  21. """
  22. DbClient DB工厂类 提供get/put/pop/delete/getAll/changeTable方法
  23. 目前存放代理的table/collection/hash有两种:
  24. raw_proxy: 存放原始的代理;
  25. useful_proxy_queue: 存放检验后的代理;
  26. 抽象方法定义:
  27. get: 随机返回一个代理;
  28. put: 放回一个代理;
  29. delete: 删除指定代理;
  30. getAll: 返回所有代理;
  31. changeTable: 切换 table or collection or hash
  32. 所有方法需要相应类去具体实现:
  33. SSDB:SsdbClient.py
  34. """
  35. __metaclass__ = Singleton
  36. def __init__(self):
  37. """
  38. init
  39. :return:
  40. """
  41. self.config = GetConfig()
  42. self.__initDbClient()
  43. def __initDbClient(self):
  44. """
  45. init DB Client
  46. :return:
  47. """
  48. __type = None
  49. if "SSDB" == self.config.db_type:
  50. __type = "SsdbClient"
  51. elif "REDIS" == self.config.db_type:
  52. __type = "RedisClient"
  53. else:
  54. pass
  55. assert __type, 'type error, Not support DB type: {}'.format(self.config.db_type)
  56. self.client = getattr(__import__(__type), __type)(name=self.config.db_name,
  57. host=self.config.db_host,
  58. port=self.config.db_port)
  59. def get(self, **kwargs):
  60. return self.client.get(**kwargs)
  61. def put(self, value, **kwargs):
  62. return self.client.put(value, **kwargs)
  63. def pop(self, **kwargs):
  64. return self.client.pop(**kwargs)
  65. def delete(self, value, **kwargs):
  66. return self.client.delete(value, **kwargs)
  67. def getAll(self):
  68. return self.client.getAll()
  69. def changeTable(self, name):
  70. self.client.changeTable(name)
  71. def get_status(self):
  72. return self.client.get_status()
  73. if __name__ == "__main__":
  74. account = DbClient()
  75. print(account.get())
  76. account.changeTable('use')
  77. account.put('ac')
  78. print(account.get())