SqlHelper.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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
  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=0)
  26. class SqlHelper(ISqlHelper):
  27. params = {'ip':Proxy.ip,'port':Proxy.port,'types':Proxy.types,'protocol':Proxy.protocol,'country':Proxy.country,'area':Proxy.area,'score':Proxy.score}
  28. def __init__(self):
  29. if 'sqlite' in DB_CONFIG['DB_CONNECT_STRING']:
  30. connect_args={'check_same_thread':False}
  31. self.engine = create_engine(DB_CONFIG['DB_CONNECT_STRING'],echo=False,connect_args=connect_args)
  32. else:
  33. self.engine = create_engine(DB_CONFIG['DB_CONNECT_STRING'],echo=False)
  34. DB_Session = sessionmaker(bind=self.engine)
  35. self.session = DB_Session()
  36. def init_db(self):
  37. BaseModel.metadata.create_all(self.engine)
  38. def drop_db(self):
  39. BaseModel.metadata.drop_all(self.engine)
  40. def insert(self,value):
  41. proxy = Proxy(ip=value['ip'],port=value['port'],types=value['types'],protocol=value['protocol'],country = value['country'],
  42. area=value['area'],speed=value['speed'])
  43. self.session.add(proxy)
  44. self.session.commit()
  45. def delete(self, conditions=None):
  46. if conditions:
  47. conditon_list = []
  48. for key in conditions.keys():
  49. if self.params.get(key,None):
  50. conditon_list.append(self.params.get(key)==conditions.get(key))
  51. conditions = conditon_list
  52. query = self.session.query(Proxy)
  53. for condition in conditions:
  54. query = query.filter(condition)
  55. deleteNum = query.delete()
  56. self.session.commit()
  57. else:
  58. deleteNum = 0
  59. return ('deleteNum',deleteNum)
  60. def update(self, conditions=None,value=None):
  61. '''
  62. conditions的格式是个字典。类似self.params
  63. :param conditions:
  64. :param value:也是个字典:{'ip':192.168.0.1}
  65. :return:
  66. '''
  67. if conditions and value:
  68. conditon_list = []
  69. for key in conditions.keys():
  70. if self.params.get(key,None):
  71. conditon_list.append(self.params.get(key)==conditions.get(key))
  72. conditions = conditon_list
  73. query = self.session.query(Proxy)
  74. for condition in conditions:
  75. query = query.filter(condition)
  76. updatevalue = {}
  77. for key in value.keys():
  78. if self.params.get(key,None):
  79. updatevalue[self.params.get(key,None)]=value.get(key)
  80. updateNum = query.update(updatevalue)
  81. self.session.commit()
  82. else:
  83. updateNum=0
  84. return {'updateNum':updateNum}
  85. def select(self, count=None,conditions=None):
  86. '''
  87. conditions的格式是个字典。类似self.params
  88. :param count:
  89. :param conditions:
  90. :return:
  91. '''
  92. if conditions:
  93. conditon_list = []
  94. for key in conditions.keys():
  95. if self.params.get(key,None):
  96. conditon_list.append(self.params.get(key)==conditions.get(key))
  97. conditions = conditon_list
  98. else:
  99. conditions=[]
  100. query = self.session.query(Proxy.ip,Proxy.port,Proxy.score)
  101. if len(conditions)>0 and count:
  102. for condition in conditions:
  103. query = query.filter(condition)
  104. return query.order_by(Proxy.score.desc(),Proxy.speed).limit(count).all()
  105. elif count:
  106. return query.order_by(Proxy.score.desc(),Proxy.speed).limit(count).all()
  107. elif len(conditions)>0:
  108. for condition in conditions:
  109. query = query.filter(condition)
  110. return query.order_by(Proxy.score.desc(),Proxy.speed).all()
  111. else:
  112. return query.order_by(Proxy.score.desc(),Proxy.speed).all()
  113. def close(self):
  114. pass
  115. if __name__=='__main__':
  116. sqlhelper = SqlHelper()
  117. sqlhelper.init_db()
  118. proxy = {'ip':'192.168.1.1','port':80,'type':0,'protocol':0,'country':u'中国','area':u'广州','speed':11.123}
  119. sqlhelper.insert(proxy)