DbClient.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 Config.ConfigGetter import config
  18. from Util import Singleton
  19. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  20. class DbClient(object):
  21. """
  22. DbClient DB工厂类 提供get/put/update/pop/delete/exists/getAll/clean/getNumber/changeTable方法
  23. 目前存放代理的有两种, 使用changeTable方法切换操作对象:
  24. raw_proxy: 存放原始的代理;
  25. useful_proxy: 存放检验后的代理;
  26. 抽象方法定义:
  27. get(proxy): 返回指定proxy的信息;
  28. put(proxy): 存入一个proxy信息;
  29. pop(): 返回并删除一个proxy信息;
  30. update(proxy): 更新指定proxy信息;
  31. delete(proxy): 删除指定proxy;
  32. exists(proxy): 判断指定proxy是否存在;
  33. getAll(): 列表形式返回所有代理;
  34. clean(): 清除所有proxy信息;
  35. getNumber(): 返回proxy数据量;
  36. changeTable(name): 切换操作对象 raw_proxy/useful_proxy
  37. 所有方法需要相应类去具体实现:
  38. ssdb: SsdbClient.py
  39. redis: RedisClient.py
  40. mongodb: MongodbClient.py
  41. """
  42. __metaclass__ = Singleton
  43. def __init__(self):
  44. """
  45. init
  46. :return:
  47. """
  48. self.__initDbClient()
  49. def __initDbClient(self):
  50. """
  51. init DB Client
  52. :return:
  53. """
  54. __type = None
  55. if "SSDB" == config.db_type:
  56. __type = "SsdbClient"
  57. elif "REDIS" == config.db_type:
  58. __type = "RedisClient"
  59. elif "MONGODB" == config.db_type:
  60. __type = "MongodbClient"
  61. else:
  62. pass
  63. assert __type, 'type error, Not support DB type: {}'.format(config.db_type)
  64. self.client = getattr(__import__(__type), __type)(name=config.db_name,
  65. host=config.db_host,
  66. port=config.db_port,
  67. password=config.db_password)
  68. def get(self, key, **kwargs):
  69. return self.client.get(key, **kwargs)
  70. def put(self, key, **kwargs):
  71. return self.client.put(key, **kwargs)
  72. def update(self, key, value, **kwargs):
  73. return self.client.update(key, value, **kwargs)
  74. def delete(self, key, **kwargs):
  75. return self.client.delete(key, **kwargs)
  76. def exists(self, key, **kwargs):
  77. return self.client.exists(key, **kwargs)
  78. def pop(self, **kwargs):
  79. return self.client.pop(**kwargs)
  80. def getAll(self):
  81. return self.client.getAll()
  82. def clear(self):
  83. return self.client.clear()
  84. def changeTable(self, name):
  85. self.client.changeTable(name)
  86. def getNumber(self):
  87. return self.client.getNumber()