MongoHelper.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import pymongo
  2. from config import DB_CONFIG, DEFAULT_SCORE
  3. from db.ISqlHelper import ISqlHelper
  4. class MongoHelper(ISqlHelper):
  5. def __init__(self):
  6. self.client = pymongo.MongoClient(DB_CONFIG['DB_CONNECT_STRING'], connect=False)
  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=DEFAULT_SCORE)
  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. if 'count' in conditions:
  39. del conditions['count']
  40. conditions_name = ['types', 'protocol']
  41. for condition_name in conditions_name:
  42. value = conditions.get(condition_name, None)
  43. if value:
  44. conditions[condition_name] = int(value)
  45. else:
  46. conditions = {}
  47. items = self.proxys.find(conditions, limit=count).sort(
  48. [("speed", pymongo.ASCENDING), ("score", pymongo.DESCENDING)])
  49. results = []
  50. for item in items:
  51. result = (item['ip'], item['port'], item['score'])
  52. results.append(result)
  53. return results
  54. if __name__ == '__main__':
  55. # from db.MongoHelper import MongoHelper as SqlHelper
  56. # sqlhelper = SqlHelper()
  57. # sqlhelper.init_db()
  58. # # print sqlhelper.select(None,{'types':u'1'})
  59. # items= sqlhelper.proxys.find({'types':0})
  60. # for item in items:
  61. # print item
  62. # # # print sqlhelper.select(None,{'types':u'0'})
  63. pass