MongoHelper.py 1.7 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'],
  15. country=value['country'],
  16. area=value['area'], speed=value['speed'], score=0)
  17. self.proxys.insert(proxy)
  18. def delete(self, conditions=None):
  19. if conditions:
  20. self.proxys.remove(conditions)
  21. return ('deleteNum', 'ok')
  22. else:
  23. return ('deleteNum', 'None')
  24. def update(self, conditions=None, value=None):
  25. # update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})
  26. if conditions and value:
  27. self.proxys.update(conditions, {"$set": value})
  28. return {'updateNum': 'ok'}
  29. else:
  30. return {'updateNum': 'fail'}
  31. def select(self, count=None, conditions=None):
  32. if count:
  33. count = int(count)
  34. else:
  35. count = 0
  36. items = self.proxys.find(filter=conditions, limit=count).sort(
  37. [("speed", pymongo.ASCENDING), ("score", pymongo.DESCENDING)])
  38. results = []
  39. for item in items:
  40. result = (item['ip'], item['port'], item['score'])
  41. results.append(result)
  42. return results