1
0

MongoHelper.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. if conditions:
  37. conditions = dict(conditions)
  38. conditions_name = ['types', 'protocol']
  39. for condition_name in conditions_name:
  40. value = conditions.get(condition_name, None)
  41. if value:
  42. conditions[condition_name] = int(value)
  43. else:
  44. conditions = {}
  45. items = self.proxys.find(conditions, limit=count).sort(
  46. [("speed", pymongo.ASCENDING), ("score", pymongo.DESCENDING)])
  47. results = []
  48. for item in items:
  49. result = (item['ip'], item['port'], item['score'])
  50. results.append(result)
  51. return results
  52. if __name__ == '__main__':
  53. # from db.MongoHelper import MongoHelper as SqlHelper
  54. # sqlhelper = SqlHelper()
  55. # sqlhelper.init_db()
  56. # # print sqlhelper.select(None,{'types':u'1'})
  57. # items= sqlhelper.proxys.find({'types':0})
  58. # for item in items:
  59. # print item
  60. # # # print sqlhelper.select(None,{'types':u'0'})
  61. pass