MongoHelper.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import pymongo
  2. from config import DB_CONFIG
  3. from db.ISqlHelper import ISqlHelper
  4. class MongoHelper(ISqlHelper):
  5. def __init__(self):
  6. self.client = pymongo.MongoClient(DB_CONFIG['DB_CONNECT_STRING'])
  7. def init_db(self):
  8. self.db = self.client.proxy
  9. self.proxys = self.db.proxys
  10. def drop_db(self):
  11. self.client.drop_database(self.db)
  12. def insert(self,value=None):
  13. if value:
  14. proxy = dict(ip=value['ip'],port=value['port'],types=value['types'],protocol=value['protocol'],country = value['country'],
  15. area=value['area'],speed=value['speed'],score=0)
  16. self.proxys.insert(proxy)
  17. def delete(self, conditions=None):
  18. if conditions:
  19. self.proxys.remove(conditions)
  20. return ('deleteNum','ok')
  21. else:
  22. return ('deleteNum','None')
  23. def update(self, conditions=None,value=None):
  24. # update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})
  25. if conditions and value:
  26. self.proxys.update(conditions,{"$set":value})
  27. return {'updateNum':'ok'}
  28. else:
  29. return {'updateNum':'fail'}
  30. def select(self, count=None,conditions=None):
  31. if count:
  32. count = int(count)
  33. else:
  34. count=0
  35. items =self.proxys.find(filter = conditions,limit = count).sort([("speed",pymongo.ASCENDING),("score",pymongo.DESCENDING)])
  36. results = []
  37. for item in items:
  38. result = (item['ip'],item['port'],item['score'])
  39. results.append(result)
  40. return results