DbClient.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. REDIS:RedisClient.py 只是对redis set的操作,不一定好复用
  35. """
  36. __metaclass__ = Singleton
  37. def __init__(self):
  38. """
  39. init
  40. :return:
  41. """
  42. self.config = GetConfig()
  43. self.__initDbClient()
  44. def __initDbClient(self):
  45. """
  46. init DB Client
  47. :return:
  48. """
  49. __type = None
  50. if "SSDB" == self.config.db_type:
  51. __type = "SsdbClient"
  52. elif "REDIS" == self.config.db_type:
  53. __type = "RedisClient"
  54. else:
  55. pass
  56. assert __type, 'type error, Not support DB type: {}'.format(self.config.db_type)
  57. self.client = getattr(__import__(__type), __type)(name=self.config.db_name,
  58. host=self.config.db_host,
  59. port=self.config.db_port)
  60. def get(self, **kwargs):
  61. return self.client.get(**kwargs)
  62. def put(self, value, **kwargs):
  63. return self.client.put(value, **kwargs)
  64. def pop(self, **kwargs):
  65. return self.client.pop(**kwargs)
  66. def delete(self, value, **kwargs):
  67. return self.client.delete(value, **kwargs)
  68. def getAll(self):
  69. return self.client.getAll()
  70. def changeTable(self, name):
  71. self.client.changeTable(name)
  72. def get_status(self):
  73. return self.client.get_status()
  74. if __name__ == "__main__":
  75. account = DbClient()
  76. print(account.get())
  77. account.changeTable('use')
  78. account.put('ac')
  79. print(account.get())