SqlHelper.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # coding:utf-8
  2. import datetime
  3. from sqlalchemy import Column, Integer, String, DateTime, Numeric, create_engine, VARCHAR
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy.orm import sessionmaker
  6. from config import DB_CONFIG, DEFAULT_SCORE
  7. from db.ISqlHelper import ISqlHelper
  8. '''
  9. sql操作的基类
  10. 包括ip,端口,types类型(0高匿名,1透明),protocol(0 http,1 https http),country(国家),area(省市),updatetime(更新时间)
  11. speed(连接速度)
  12. '''
  13. BaseModel = declarative_base()
  14. class Proxy(BaseModel):
  15. __tablename__ = 'proxys'
  16. id = Column(Integer, primary_key=True, autoincrement=True)
  17. ip = Column(VARCHAR(16), nullable=False)
  18. port = Column(Integer, nullable=False)
  19. types = Column(Integer, nullable=False)
  20. protocol = Column(Integer, nullable=False, default=0)
  21. country = Column(VARCHAR(100), nullable=False)
  22. area = Column(VARCHAR(100), nullable=False)
  23. updatetime = Column(DateTime(), default=datetime.datetime.utcnow)
  24. speed = Column(Numeric(5, 2), nullable=False)
  25. score = Column(Integer, nullable=False, default=DEFAULT_SCORE)
  26. class SqlHelper(ISqlHelper):
  27. params = {'ip': Proxy.ip, 'port': Proxy.port, 'types': Proxy.types, 'protocol': Proxy.protocol,
  28. 'country': Proxy.country, 'area': Proxy.area, 'score': Proxy.score}
  29. def __init__(self):
  30. if 'sqlite' in DB_CONFIG['DB_CONNECT_STRING']:
  31. connect_args = {'check_same_thread': False}
  32. self.engine = create_engine(DB_CONFIG['DB_CONNECT_STRING'], echo=False, connect_args=connect_args)
  33. else:
  34. self.engine = create_engine(DB_CONFIG['DB_CONNECT_STRING'], echo=False)
  35. DB_Session = sessionmaker(bind=self.engine)
  36. self.session = DB_Session()
  37. def init_db(self):
  38. BaseModel.metadata.create_all(self.engine)
  39. def drop_db(self):
  40. BaseModel.metadata.drop_all(self.engine)
  41. def insert(self, value):
  42. proxy = Proxy(ip=value['ip'], port=value['port'], types=value['types'], protocol=value['protocol'],
  43. country=value['country'],
  44. area=value['area'], speed=value['speed'])
  45. self.session.add(proxy)
  46. self.session.commit()
  47. def delete(self, conditions=None):
  48. if conditions:
  49. conditon_list = []
  50. for key in list(conditions.keys()):
  51. if self.params.get(key, None):
  52. conditon_list.append(self.params.get(key) == conditions.get(key))
  53. conditions = conditon_list
  54. query = self.session.query(Proxy)
  55. for condition in conditions:
  56. query = query.filter(condition)
  57. deleteNum = query.delete()
  58. self.session.commit()
  59. else:
  60. deleteNum = 0
  61. return ('deleteNum', deleteNum)
  62. def update(self, conditions=None, value=None):
  63. '''
  64. conditions的格式是个字典。类似self.params
  65. :param conditions:
  66. :param value:也是个字典:{'ip':192.168.0.1}
  67. :return:
  68. '''
  69. if conditions and value:
  70. conditon_list = []
  71. for key in list(conditions.keys()):
  72. if self.params.get(key, None):
  73. conditon_list.append(self.params.get(key) == conditions.get(key))
  74. conditions = conditon_list
  75. query = self.session.query(Proxy)
  76. for condition in conditions:
  77. query = query.filter(condition)
  78. updatevalue = {}
  79. for key in list(value.keys()):
  80. if self.params.get(key, None):
  81. updatevalue[self.params.get(key, None)] = value.get(key)
  82. updateNum = query.update(updatevalue)
  83. self.session.commit()
  84. else:
  85. updateNum = 0
  86. return {'updateNum': updateNum}
  87. def select(self, count=None, conditions=None):
  88. '''
  89. conditions的格式是个字典。类似self.params
  90. :param count:
  91. :param conditions:
  92. :return:
  93. '''
  94. if conditions:
  95. conditon_list = []
  96. for key in list(conditions.keys()):
  97. if self.params.get(key, None):
  98. conditon_list.append(self.params.get(key) == conditions.get(key))
  99. conditions = conditon_list
  100. else:
  101. conditions = []
  102. query = self.session.query(Proxy.ip, Proxy.port, Proxy.score)
  103. if len(conditions) > 0 and count:
  104. for condition in conditions:
  105. query = query.filter(condition)
  106. return query.order_by(Proxy.score.desc(), Proxy.speed).limit(count).all()
  107. elif count:
  108. return query.order_by(Proxy.score.desc(), Proxy.speed).limit(count).all()
  109. elif len(conditions) > 0:
  110. for condition in conditions:
  111. query = query.filter(condition)
  112. return query.order_by(Proxy.score.desc(), Proxy.speed).all()
  113. else:
  114. return query.order_by(Proxy.score.desc(), Proxy.speed).all()
  115. def close(self):
  116. pass
  117. if __name__ == '__main__':
  118. sqlhelper = SqlHelper()
  119. sqlhelper.init_db()
  120. proxy = {'ip': '192.168.1.1', 'port': 80, 'type': 0, 'protocol': 0, 'country': '中国', 'area': '广州', 'speed': 11.123, 'types': ''}
  121. sqlhelper.insert(proxy)
  122. sqlhelper.update({'ip': '192.168.1.1', 'port': 80}, {'score': 10})
  123. print(sqlhelper.select(1))